我以为我解决了一个问题,但现在我面临另一个问题...... VBA太难了。
For i = 2 To LastRow
For j = 2 To LastCol
'
'*There is lots of code here....*
'
salk = Sheets("SheetS").Cells(i, j).Value
presence = WorksheetFunction.CountIf(Range("B1:D19"), salk)
Dim arrOutput(2)
Select Case presence
Case 1
Sheets("SheetX").Cells(i, j).Value = salk & " (" & GroupCol(salk) & ")"
Case 2
arrOutput(0) = Int(GroupCol(salk) / presence)
arrOutput(1) = GroupCol(salk) - arrOutput(0)
arrOutput(2) = 0
Sheets("SheetX").Cells(i, j).Value = salk & " (" & arrOutput(0) & " - " & arrOutput(1) & ")"
Case Else
MsgBox "Error"
End Select
Next j
Next i
通过上面的代码,我设法得到了这个结果:
我对将奇数分成两个不同数字的代码非常满意。所以我不必把人减半。当一个组的偶数数字作为结果时,它可以分成两个相同的数字。当它的奇数数字时,它变得非常困难。戴夫帮助我解决了如何修复奇数问题。我在我的代码中实现了Dave的代码。您会看到括号中的所有内容都是属于某个团队的组中的总人数。你看到4a4总共有39个。因为这个组出现了两次我想把这个组分成两组。当我这样做时我得到18.5,Dave的代码(上面实现的)让我能够获得以下两个数字19和20。 我的问题是在两个组中得到这两个单独的数字,团队名称C的组得到19(参见图中的B2),另一个数字20转到B6。调整后,我得到以下图像:
因为select case在循环中我不能将它们保存到单独的变量中:(...有没有办法得到我想要的东西。
答案 0 :(得分:1)
我有一个潜在的解决方案(花了我一些时间,算法质量不太好)
而不是:
Sheets("SheetX").Cells(i, j).Value = salk & " (" & arrOutput(0) & " - " & arrOutput(1) & ")"
在Case 2
你可以尝试(你必须调整我的代码,我在个人的例子中尝试过):
' ====== ALGO START
' The following calculate the number of times salk appears before the current cell
Select Case i ' Depends on the ROWS since you CAN'T use a range which is not continuous with COUNTIF!
Case 1
presenceCurr = WorksheetFunction.CountIf(Range("B1" & ":" & Cells(i, j).Address), salk)
Case 2
presenceCurr = WorksheetFunction.CountIf(Range("B2" & ":" & Cells(i, j).Address), salk) _
+ WorksheetFunction.CountIf(Range("B1:D1"), salk)
Case 3
presenceCurr = WorksheetFunction.CountIf(Range("B3" & ":" & Cells(i, j).Address), salk) _
+ WorksheetFunction.CountIf(Range("B1:D2"), salk)
Case 5
' etc ...
' All the other Cases
Case 19
presenceCurr = WorksheetFunction.CountIf(Range("B19" & ":" & Cells(i, j).Address), salk) _
+ WorksheetFunction.CountIf(Range("B1:D18"), salk)
Case Else ' Should not happen
MsgBox "Error, out of range"
End Select
presenceCurr = presenceCurr - 1 ' Minus 1 because the current cell would be counted
' ===== ALGO END
Sheets("SheetX").Cells(i, j).Value = salk & " (" & arrOutput(presenceCurr) & ")"
我不能完全确定这会起作用,因为我认为"B1:D19"
与您的嵌套for循环相关联(就范围而言)。
如前所述,您可能需要调整此代码。重要的是这个想法:我发现在当前单元格之前找到了多少次salk(在你的例子中它将是0或1)并将其与数组中的位置相关联(:
Select Case
可能真的更短了我已经循环了Columns然后行......但
注意:这是一个快速而肮脏的代码,我可以明确优化和分解(例如使用for
循环代替select case
)
无论如何,我希望这会有所帮助,你可以用它来做你想做的事情