如何在此代码中使用 Do While Loop / While End While Loop 而不是 GoTo

How to use Do While Loop / While End While Loop in this code instead of GoTo

我对 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

想法是在找到数组中的数字后循环:

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

使用字典。

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