可以嘗試下面,你將需要添加一個引用到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