[英]VBA Excel “random” two column generator
I'm generating a "random" (with no repeats) list of the questions using the following: 我使用以下方法生成问题的“随机”(无重复)列表:
Sub randomCollection()
Dim Names As New Collection
Dim lastRow As Long, i As Long, j As Long, lin As Long
Dim wk As Worksheet
Set wk = Sheets("Sheet1")
With wk
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
For i = 2 To lastRow
Names.Add wk.Cells(i, 1).Value, CStr(wk.Cells(i, 1).Value)
Next i
lin = 1
For i = lastRow - 1 To 1 Step -1
j = Application.WorksheetFunction.RandBetween(1, i)
lin = lin + 1
Range("B" & lin) = Names(j)
Names.Remove j
Next i
End Sub
I'm stuck on how to pick up data in column B
, and generate it with the corresponding data in column A
. 我被困在如何获取B
列中的数据,以及如何使用A
列中的相应数据生成数据A
。
For example, A1
and B1
need to stay together on the "random" list, as does A2
, B2
, etc. 例如, A1
和B1
以及A2
, B2
等都需要在“随机”列表上保持在一起。
If I understand your task correctly, you want to take whatever is in column A and put it in column B in random locations, not including a header row. 如果我正确地理解了您的任务,那么您希望将A列中的内容全部放入B列中的任意位置,不包括标题行。 If this is the case, try this: 如果是这种情况,请尝试以下操作:
Sub randomCollection()
Dim wrk As Worksheet, source As Long, dest As Long, lastRow As Long, i As Long, rowCount As Long
Set wrk = ActiveWorkbook.ActiveSheet
lastRow = wrk.Rows.Count
lastRow = wrk.Range("A1:A" & Trim(Str(lastRow))).End(xlDown).Row
'First, clear out the destination range
wrk.Range("B2:B" + Trim(Str(lastRow))).Clear
source = 2
Do Until source > lastRow
dest = Application.WorksheetFunction.RandBetween(1, lastRow - source + 1)
'Find the blank row corresponding to it
rowCount = 1
For i = 2 To lastRow
If dest = rowCount And wrk.Cells(i, 2) = "" Then
wrk.Cells(i, 2) = wrk.Cells(source, 1)
Exit For
End If
If wrk.Cells(i, 2) = "" Then '2 is column B
rowCount = rowCount + 1
End If
Next
source = source + 1
Loop
End Sub
This looks for the first random blank space in column B to put each cell in column A. 这将在B列中查找第一个随机空白,以将每个单元格放入A列中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.