【问题标题】:How to use Do While Loop / While End While Loop in this code instead of GoTo如何在此代码中使用 Do While 循环 / While End While 循环而不是 GoTo
【发布时间】:2020-02-18 13:50:52
【问题描述】:

我对 Visual Basic 有点陌生,我正在尝试制作一个程序,该程序将生成从 1 到 9 的随机数,而无需使用数组重复。我还读到过,可以使用 Do While Loop 或 While End While 语句,而不是使用 GoTo 语句(因为它们通常不受欢迎)。我试过使用这些循环,但没有成功。代码如下:

Dim x As Integer = 0, y As Integer = 0, num As Integer = 0, arr(8) As Integer
        lstLoop.Items.Clear()
        For x = 0 To 8 
Start:
            Randomize()
            num = Fix(Rnd() * 9) + 1
            For y = 0 To 8
                If num = arr(y) Then
                    GoTo Start
                End If
            Next
        arr(x) = num
        lstLoop.Items.Add(arr(x))
        Next

【问题讨论】:

    标签: vba goto


    【解决方案1】:

    这个想法是在你找到数组中的数字时循环:

    Sub GenerateRandom()
    
    Dim x As Integer
    Dim num As Integer
    Dim arr(8) As Integer
    
    Randomize Timer
    
    For x = 0 To 8
        Do
            num = Fix(Rnd() * 9) + 1
        Loop While FindInArray(arr, x - 1, num)
    
        arr(x) = num
    Next x
    
    End Sub
    
    Function FindInArray(arr() As Integer, maxIndex As Integer, num As Integer) As Boolean
    
    Dim i As Integer
    FindInArray = False
    
    For i = 0 To maxIndex
        If arr(i) = num Then
            FindInArray = True
            Exit Function
        End If
    Next
    
    End Function
    

    【讨论】:

      【解决方案2】:

      使用字典。

      Sub test()
          Dim dic As Object
          Dim n As Integer
          Dim Num As Integer
          Set dic = CreateObject("Scripting.Dictionary")
      
          Do Until n = 9
              num = WorksheetFunction.RandBetween(1, 9)
              If dic.Exists(num) Then
              Else
                  n = n + 1
                  dic.Add num, num
              End If
      
          Loop
          Range("a1").Resize(1, 9) = dic.Keys
      End Sub
      

      Sub test()
          Dim dic As Object
          Dim Num As Integer
          Set dic = CreateObject("Scripting.Dictionary")
      
          Do Until dic.Count = 9
              num = WorksheetFunction.RandBetween(1, 9)
              If dic.Exists(num) Then
              Else
                  dic.Add num, num
              End If
          Loop
          Range("a1").Resize(1, 9) = dic.Keys
      End Sub
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-18
        • 1970-01-01
        • 2021-07-27
        • 2016-02-21
        • 1970-01-01
        • 2020-08-28
        • 1970-01-01
        相关资源
        最近更新 更多