Vba 按总数分组数据
假设我可以使用下表:Vba 按总数分组数据,vba,excel,excel-formula,Vba,Excel,Excel Formula,假设我可以使用下表: project name total units a 3 b 4 c 1 d 5 e 2 f 5 g 8 h 12 i 8 j 10 k 4 l
project name total units
a 3
b 4
c 1
d 5
e 2
f 5
g 8
h 12
i 8
j 10
k 4
l 7
m 9
n 19
o 15
p 6
q 3
例如,我希望将项目名称与不超过20个的总单位分组。所以,如果我把项目a加起来,加上f,我总共会得到20个。因此,Excel将对这组项目进行分组并为其指定唯一标识符 我想很容易地确定具体项目的文件号。因此,只要我输入项目名称和总单位,它就可以向我返回一个数字,告诉我项目应该进入哪个文件号
project name total units file number
a 3 1
b 4 1
c 1 1
d 5 1
e 2 1
f 5 1
g 8 2
h 12 2
i 8 3
j 10 3
k 4 4
l 7 4
m 9 4
n 19 5
o 15 6
p 6 7
q 3 7
我想要的最终结果是,对总单位进行汇总,对总和等于或小于20的项目名称进行分组,并给出一个文件号
有可能让Excel做这样的事情吗?好吧,根据barryleajo提到的但书,假设你的个人总单位在1到19之间,你需要这个算法,我认为:-
If it's the first line of data
Running total=total units
Else
If (Previous running total + total units) > 20
Running total=total units
Else
Running total=Previous running total + total units
在下面的电子表格中,我将D2=B2,E2=1
然后把公式
=如果(D2+B3>20,B3,D2+B3)
进入D3
及
=如果(B3=D3,E2+1,E2)
进入E3,把他们拉下来
以下代码有效。我添加了注释以帮助您理解答案
Dim total_units As Range
Dim file_number As Integer
Dim cumulative_sum As Integer
Sub filenumber()
'Fill in column C header with string 'file_number'
Range("C1") = "file_number"
'Set total_units as the range variable
Set total_units = ThisWorkbook.Sheets(1).Range("B2")
'File_number starts equal to 1
file_number = 1
'Cumulative sum starts in the first row of total_units
cumulative_sum = total_units
'Loop until non empty rows of column project_name
Do While Not total_units = ""
'Fill in column C
total_units.Offset(, 1) = file_number
'Records the cumulative_sum in the row
cumulative_sum = cumulative_sum + total_units.Offset(1, 0)
'If cumulative sum exceeds 20, then, `file_number` changes and the start point in `cumulative_sum` also changes
If cumulative_sum > 20 Then
cumulative_sum = total_units.Offset(1, 0)
file_number = file_number + 1
End If
'Move the range
Set total_units = total_units.Offset(1, 0)
'Next row
Loop
End Sub
不要使用VBA,这是使用Excel内置函数可以轻松实现的。
SUMIF()
函数在这里会有很大帮助
将以下公式放入单元格C2(假设上述设置)
公式执行以下操作:
- 如果名称为“a”,则根据“a”中的单位检查需要多少文件
- 对于所有其他名称:将当前文件中以前的单位相加(即上面单元格中的文件编号),然后添加当前项目单位。如果编号超过20,则在文件编号中添加1,否则使用相同的文件编号
=IF(A2="a",ROUNDDOWN((B2-1)/20,0)+1,IF(SUMIF($C1:C$2,C1,$B1:B$2)+B2>20,C1+1,C1))