2015-05-29 62 views
2

我不熟悉使用宏的,但我认为我最想要执行的操作最好是用宏处理。所以我可以使用您可能拥有的所有输入!根据类别从列表中随机选择一个项目,根据不同的数字重复次数

我有这些标题;

ID标签笔性别体重类的内部范围

450行数据。根据体重数据的分布情况,我在其他两列(班级和数量)中列出了每个班级要选择的行数。所选行在“内部范围”列中必须具有值“是”。

我想根据每个类所需的数量随机选择行,并将这些行复制到新工作表。它在新表中总计最多30行。

我希望你有一个建议如何完成这个动作!

+0

会[你可以给你一个很好的开始,你的宏?] [这个问题/答案](http://stackoverflow.com/questions/7542617/non-repeating-random-number-generator)据我可以告诉你想要选择1到450之间的30个随机唯一数字,并将相应的行复制到另一个表单中? – eirikdaude

+0

是的,但我确实想根据重量分布为不同类别选择一定的数字。例如对于一个类别为2,对另一个类别为4等等。不同类别的编号也显示在Excel表格中。 –

+0

所以你想选择x个随机行,满足标准和z?我会这样做的方式只是选择一个随机行,检查它是否符合标准,然后继续下一个行,直到我找到足够的。当然,如果范围划分得足够好以至于你不必搜索所有450行,那就更好了,但是这样小的数据大小对性能的影响应该可以忽略不计。 – eirikdaude

回答

0

可以尝试下面,你将需要添加一个引用到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 

对不起存在一些错误或错别字,我从我的手机写道。

相关问题