我试图用这段代码循环一个子,直到B9有一个值。 并且我不确定我做错了什么,直到我包含了while语句。
Private Sub CommandButton2_Click()
Range("B5:B18").ClearContents
If [D2] = [R15] Then
Do While IsEmpty("B9") = True
Randomname
Loop
End If
同时发布sub的代码,因为它可能是相关的。 sub是一个随机名称选择器,基于我找到并根据我的需求修改的代码。它比较了两个范围,并从尚未使用的源范围中提取名称,一次一个名称。
Sub Randomname()
Dim source, destination As Range
Set source = ActiveSheet.Range("L15:L28")
Set destination = ActiveSheet.Range("B5:B18")
ReDim randoms(1 To source.Rows.Count)
destrow = 0
For i = 1 To destination.Rows.Count
If destination(i) = "" Then: destrow = i: Exit For
Next i
If destrow = 0 Then: MsgBox "no more room in destination range": Exit Sub
For i = 1 To UBound(randoms): randoms(i) = Rnd(): Next i
ipick = 0: tries = 0
Do While ipick = 0 And tries < UBound(randoms)
tries = tries + 1
minrnd = WorksheetFunction.Min(randoms)
For i = 1 To UBound(randoms)
If randoms(i) = minrnd Then
picked_before = False
For j = 1 To destrow - 1
If source(i) = destination(j) Then: picked_before = True: randoms(i) = 2: Exit For
Next j
If Not picked_before Then: ipick = i
Exit For
End If
Next i
Loop
If ipick = 0 Then: MsgBox "no more unique name possible to pick": Exit Sub
destination(destrow) = source(ipick)
End Sub
答案 0 :(得分:0)
看起来你的语法错误
If destination(i) = "" Then: destrow = i: Exit For
你最好用
If desination(i) = "" Then
destrow = i
Exit For
End If
使用冒号在同一行上运行多个命令时,请确保语法正确。我个人更喜欢将每个命令保留在自己的行上,因此我的代码更容易阅读。这对循环尤为重要。
最后,如果您只想使用then语句运行一个命令,则可以在不使用冒号之后键入它。否则,使用if块。
例如
If True = True then msgbox "True"
或多个命令
If True = True Then
msgbox "True"
msgbox "Not False"
End if
它更安全,它使您的代码更容易理解。