【发布时间】:2026-02-05 21:30:02
【问题描述】:
早安,
我有一个表格,其中包含以下格式的每个部门每周的销售额:
Week1 Week2 Week3 ...
Dept1 10 20 10
Dept1 20 10 30
Dept1 30 30 20
Dept2 20 20 30
Dept2 20 20 10
Dept3 50 40 60
...
我需要做的是创建一个较小的报告来汇总每个部门的销售额。按照以下模板:
Week1 Week2 Week3
Dept1 60 60 60
Dept2 40 40 40
Dept3 50 40 60
Total 150 140 160
每个部门的行数各不相同。然后这个报告应该打印在电子表格上。
据我了解,这可以使用字典或集合来完成。到目前为止,我已经设法计算出每周的总和,但是,我不明白如何将这些结果转移到工作表中。我尝试将总和转移到数组中,但没有成功。
这是我到目前为止的代码。它正确计算每周的总和,然后清空集合并再次计算下一周的总和。所以,我遇到的主要问题是如何将这些结果写入工作表。
Dim collection As collection
Dim dataitems As Itemlist 'defined in classmodule
Dim key As String
Dim item As Double
Dim row As Long, column As Long
Dim lstrow As Long, lstcolumn As Long
Set collection = New collection
columnindex = 3 'that is the column where name of departments appear
lstrow = Sheet1.Cells(Sheet1.Rows.Count, column).End(xlUp).row
lstcolumn = Sheet1.Cells(1, Sheet1.Columns.Count).End(xlToLeft).column
For column = 5 To lstcolumn 'column 5 is where the weekly data start
For row = 2 To lstrow 'first 1 contains titles
key = CStr(Sheet1.Cells(row, "C").Value2)
item = CDbl(Sheet1.Cells(row, column).Value2)
Set dataitems = Nothing: On Error Resume Next
Set dataitems = collection(key): On Error GoTo 0
If dataitems Is Nothing Then
Set dataitems = New Itemlist
dataitems.key = key
collection.Add dataitems, key
End If
With dataitems
.Sum = .Sum + item
.Itemlist.Add item
End With
Next
Set collection = New collection
Next
感谢任何帮助。谢谢。
【问题讨论】:
-
通常使用 PivotTable support.office.com/en-us/article/… 或数据选项卡 > 合并
-
@Slai 是的,我已经使用 Pivot 表了,但我们的想法是避免它
标签: arrays vba dictionary collections