【发布时间】:2016-07-07 10:08:43
【问题描述】:
我需要帮助才能从具有特定条件的另一个工作表中获取随机数据
类似这样的:
如果我单击一个按钮或运行一个宏,我应该从rawdata.xlsx "Sheet1" 工作表中获取4 random samples for all rows that has AA、1 random sample for all rows that has BB、1 random sample for all rows that has CC、3 random samples for all rows that has DD 和1 random sample for all rows that has EE 并将其粘贴到tool.xlsm "Random Sample" 工作表中。
一切都应该一键完成。
到目前为止,这是我的代码。我只能在整个工作表中获得特定数量的随机数据。我希望有人可以为我编辑此代码或提供代码来帮助我并能够做出我想做的事情。提前致谢
Sub CopyRandomRows()
Sheets("Random Sample").Select
Cells.Select
Range("C14").Activate
Selection.Delete Shift:=xlUp
Windows("rawdata.xlsx").Activate
Rows("1:1").Select
Selection.Copy
Application.CutCopyMode = False
Selection.Copy
Windows("tool.xlsm").Activate
Sheets("Random Sample").Select
Rows("1:1").Select
ActiveSheet.Paste
Dim source As Range, target As Range, randCount&, data(), value, r&, rr&, c&
'this defines the source to take the data
Set source = Workbooks("rawdata.xlsx").Worksheets("Sheet1").Range("A2:L5215")
'this defines the target to paste the data
Set target = Workbooks("tool.xlsm").Worksheets("Random Sample").Range("A2")
'this defines the number of rows to generate based on the input in textbox
randCount = 20
'this loads the data in an array
data = source.value
'this shuffles the rows
For r = 1 To randCount
rr = 1 + Math.Round(VBA.rnd * (UBound(data) - 1))
For c = 1 To UBound(data, 2)
value = data(r, c)
data(r, c) = data(rr, c)
data(rr, c) = value
Next
Next
'this writes the data to the target
target.Resize(randCount, UBound(data, 2)) = data
End Sub
【问题讨论】:
标签: vba random macros conditional-statements