我想用這個代碼循環一個子直到B9有一個值。 我不確定我在做什麼錯誤的子作品,直到我包括while語句。Excell用while循環重複一個子呼叫
Private Sub CommandButton2_Click()
Range("B5:B18").ClearContents
If [D2] = [R15] Then
Do While IsEmpty("B9") = True
Randomname
Loop
End If
另外發布代碼爲子,因爲它可能是相關的。 這個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
'IsEmpty(「B9」)'將始終返回false。您可能正在尋找'IsEmpty([B9])'。 – Comintern
好吧,你讓我在正確的方向思考,這使它的工作。 儘管IsEmpty(範圍(「B9」),值)=真 謝謝。 – user3107457
@ user3107457請注意,IsEmpty(Range(「B9」)。Value)= True'與IsEmpty([B9])'相同。 ('= True'部分是多餘的,因爲如果它本身爲'True',並且'[B9]'是'Range(「B9」)的快捷方式,那麼它只等於'True'。)。 – YowE3K