【发布时间】:2018-01-02 05:41:09
【问题描述】:
我正在研究随机数 VBA,下面的代码从 sheet2 中选择一个名称并复制到表 1,我可以重复这些步骤从该列表中选择 3 个不同的名称。当所有三个名称都在三个连续行中时,此代码做得非常好,但是当它们在第 5 行、第 10 行和第 15 行时未能选择 3 个不同的名称。有人可以帮我挑选三个不同的名字并将它们放在相隔 5 行的行中吗? (第 1 行第 1 个名称,第 5 行第 2 个名称和第 15 行第 3 个名称)我是 VBA 新手!
Sub DDQ1()
Application.ScreenUpdating = False
Dim source, destination As Range
Set source = Sheets("sheet2").Range("A60:A81")
Sheets("sheet1").Activate
Set destination = ActiveSheet.Range("B53")
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)
Application.ScreenUpdating = True
End Sub
【问题讨论】:
-
不是您问题的答案,但
Dim source, destination As Range将使目标成为一个范围,但源作为变体。你需要Dim source as Range, destination As Range -
稍微格式化一下会有很大帮助。