VBA - 按组分配插槽



我有不同数量的插槽(如"运动场"(,并且必须将它们分配给不同数量的组(例如,4个场地,用于2组,因此每个组被分配2个场地进行游戏(。

一开始,我认为我可以通过在Excel中通过将"运动场"的数量除以组的数量然后向下舍入来绕过它:

= ROUNDDOWN(B6/B5;0)

但是现在,如果数字不"合适",就会有空字段。

我可以在 Excel 或 VBA 中执行此操作(但我想 VBA 会更实用(。

我尝试在谷歌上搜索结果,但我无法弄清楚"谷歌搜索什么"。我猜这个问题已经被其他人以不同的名称/用途解决了。

有没有人对如何处理这个问题有任何指示?尤其是在团体数量和"运动场"数量各不相同的情况下?我想在Excel中使用VBA自动分配。

提前致谢

我不知道你想要实现什么,但这里有一个代码,它将帮助您分配所有字段。试试这个:

Sub AssignSlots()
    Dim groupCount As Long, fieldCount As Long, rest As Long, fieldsPerGroup As Long, i As Long
    groupCount = 6 'Range("B6").Value
    fieldCount = 10 'Range("B5").Value
    'if we don't have enought fields, exit program
    If fieldCount < groupCount Then
        MsgBox "There are less fields than groups!"
        Exit Sub
    End If
    'calculate how many fields per group (Int(...) performs rounding down)
    fieldsPerGroup = Int(fieldCount / groupCount)
    'calculate rest of fields
    rest = fieldCount - fieldsPerGroup * groupCount
    For i = 1 To rest
        'assign fieldsPerGroup + 1 fields to groups
    Next
    For i = rest + 1 To groupCount
        'assign fieldsPerGroup fields to rest of groups
    Next
End Sub

在上述程序中,组 1-4 将分配 2 个字段,组 5 和 6 将分配 1 个字段。

最新更新