【问题标题】:Randomly select an item from a list based on a class, repeat number of times based on different numbers根据类别从列表中随机选择一个项目,根据不同的数字重复次数
【发布时间】:2015-05-29 11:48:54
【问题描述】:

我不熟悉使用宏,但我认为我希望 excel 执行的操作最好使用宏来处理。所以我可以使用你可能有的所有输入!

我有这些标题;

ID 标签笔性别重量等级范围内

有 450 行数据。根据权重数据的分布,我在另外两列(类和数字)中有我想在每个类中选择的行数。所选行在“范围内”列中的值必须为“是”。

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

希望您对如何完成此操作有建议!

【问题讨论】:

  • this question / answer 能否为您的宏提供一个良好的开端?据我所知,您想在 1 到 450 之间选择 30 个随机的唯一数字,并将相应的行复制到不同的工作表中?
  • 是的,但我确实想根据重量分布为不同的类别选择一个特定的数字。例如,一个班级 2 个,另一个班级 4 个,等等。不同班级的数字也在 Excel 表中注明。
  • 所以你想选择x个随机行,满足条件和z?我这样做的方法就是选择一个随机行,检查它是否满足标准,然后继续下一个,直到找到足够的。当然,如果范围划分得足够好,您不必搜索所有 450 行,那就更好了,但是如此小的数据量对性能的影响应该可以忽略不计。

标签: vba excel


【解决方案1】:

您可以尝试以下方法吗,您需要添加对 Microsoft Scripting Runtime 库的引用:

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

抱歉,如果有一些错误或拼写错误,我是用手机写的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-21
    • 2021-10-12
    • 2013-03-22
    • 1970-01-01
    • 2017-02-19
    • 2017-05-19
    • 1970-01-01
    • 2016-05-05
    相关资源
    最近更新 更多