如何将excel中的一些可用数据(一百万个条目)随机分配到一组10列/行?



我有一列员工的"ID"(大约 100 万个条目(,我想将它们随机分配到新的 excel 工作表中的新 10 行/列。

例如:

Card ID  
123
132
143
...

我想将此数据随机分配到新的 excel 工作表中的 10 个新列/行(任何可行的(。

此过程是实现此目的的几种方法之一:

Sub randomColumns()
Const inputSheet = "Sheet1" 'name of the sheet with the million values
Const inputColumn = 1 'column # where the million values are
Const inputStartRow = 1 'rows # of the first value
Const outputColumns = 10 'number of columns randomize into
Dim wsIn As Worksheet, wsOut As Worksheet
Dim rw As Long, inValue As Variant, outCol As Long
Set wsIn = Sheets(inputSheet) 'setup worksheets
Set wsOut = ActiveWorkbook.Worksheets.Add 'create new worksheet
rw = inputStartRow
Randomize 'seed random number generator
With wsOut
Do
inValue = wsIn.Cells(rw, inputColumn) 'get the value to move
outCol = Int(Rnd() * outputColumns) + 1 'pick random column
.Cells(Application.WorksheetFunction. _
CountA(.Columns(outCol)) + 1, outCol) = inValue 'move value
wsIn.Cells(rw, inputColumn) = "" 'remove value from old location
rw = rw + 1 'next input row
Loop While wsIn.Cells(rw, inputColumn) <> "" 'loop until blank cell
End With
MsgBox "Randomized " & rw - 1 & " items to worksheet '" & wsOut.Name & "'."
End Sub

将常量inputSheet的值更改为包含值的工作表的名称。如有必要,更改其他常量,否则它将开始查找A1inputSheet的值。

将创建一个新工作表,然后将每个数字放在随机选择的列中值的底部,然后从inputSheet中删除。

这将持续到在inputSheet上遇到空白单元格。


更多信息:

  • MSDN:随机化语句
  • MSDN :Rnd(( 函数
  • MSDN :WorksheetFunction.CountA Method(Excel/VBA(
  • MSDN :Sheets.Add Method(Excel(

最新更新