按数据分组数据

假设我有下面的表格来处理:

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给出一个唯一的标识符。

我想轻松确定具体项目进入哪个文件编号。 所以只要我input项目名称和总单位,它就可以返回一个数字给我说明项目应该进入哪个文件编号。

 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做这样的事情?

不要用VBA做什么,你可以用Excel的内置函数轻松做什么。 SUMIF()函数在这里会有很多帮助

将下面的公式放入单元格C2 (假设上面的设置)

 =IF(A2="a",ROUNDDOWN((B2-1)/20,0)+1,IF(SUMIF($C1:C$2,C1,$B1:B$2)+B2>20,C1+1,C1)) 

该公式正在执行以下操作:

  • 如果名称是“a”,则根据“a”中的单位检查需要多less个文件
  • 对于所有其他名称:将当前文件中的前几个单元(即上面单元格中的文件编号)相加并添加当前项目单位。 如果数量超过20,则将文件编号加1,否则使用相同的文件编号

我已经testing过这个,但是如果你有任何问题,请告诉我。

好吧,以barryleajo提到的条件和假设你的个人总单位是1和19之间,你需要这个algorithm,我认为: –

 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,

然后把公式

= IF(D2 + B3> 20,B3,D2 + B3)

进入D3

= IF(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