可以尝试下面,你将需要添加一个引用到Microsoft脚本运行时库:
如果
Const rowCount = 450
Public Sub copyRows()
Dim i As Integer
Dim j As Integer
Dim classes As Scripting.Dictionary
Dim source As Worksheet
Dim colNumber As Integer
Dim colClassName as Integer
Dim colInsideRange As Integer
Dim allSelected As Boolean
Dim randomRow as Integer
Dim sumRemaining as Integer
allSelected = False
Set source = Worksheets("YourWorksheetName")
colClassName = 6 'this is the column number where class names are entered. I am assuming 6
colNumber = 7 'this is the column number where number of rows to be selected are entered. I am assuming 7
colInsideRange = 8 'this is the column number where "Inside Range" values are entered. I am assuming 9
For i = 2 to rowCount + 1 'assuming you have a header row
classes(CStr(source.Cells(i, colClassName))) = CInt(source.cells(i, colNumber)
Next i
Do until allSelected
Randomize
randomRow = Int ((Rnd * 450) + 2) 'assuming you have a header row, + 1 if you don't
If classes(CStr(source.Cells(randomRow, colClassName))) = 0 Then
With classes
sumRemaining = 0
For j = 1 to .Count - 1
sumRemaining = sumRemaining + .Items(j)
If sumRemaining > 0 Then Exit For
Next j
allSelected = (sumRemaining = 0)
End With
Else
source.Cells(randomRow, colInsideRange) = "Yes"
classes(CStr(source.Cells(randomRow, colClassName))) = classes(CStr(source.Cells(randomRow, colClassName))) - 1
End If
Loop
'Enter your code to copy rows with "Inside Range" = "Yes"
End Sub
对不起存在一些错误或错别字,我从我的手机写道。
会[你可以给你一个很好的开始,你的宏?] [这个问题/答案](http://stackoverflow.com/questions/7542617/non-repeating-random-number-generator)据我可以告诉你想要选择1到450之间的30个随机唯一数字,并将相应的行复制到另一个表单中? – eirikdaude
是的,但我确实想根据重量分布为不同类别选择一定的数字。例如对于一个类别为2,对另一个类别为4等等。不同类别的编号也显示在Excel表格中。 –
所以你想选择x个随机行,满足标准和z?我会这样做的方式只是选择一个随机行,检查它是否符合标准,然后继续下一个行,直到我找到足够的。当然,如果范围划分得足够好以至于你不必搜索所有450行,那就更好了,但是这样小的数据大小对性能的影响应该可以忽略不计。 – eirikdaude