|
本帖最后由 zorsite 于 2017-12-22 13:45 编辑
这种需求真的应该用数据透视表,不需要编程,只需要鼠标点点就能够完成你的数据汇总工作,强烈建议楼主研究研究。
用VBA可以满足你的需求,但是你的需求会变化,会不断有新需求、新想法。要么学好VBA撸袖子自己干,要么用数据透视表。
以下代码在ivccav的基础上修改而来,感谢ivccav提供了最核心的思路和功能。
代码没有考虑累计销售、报表日销售和最后一行的小计。
- Option Explicit
- Sub 数组整体写入()
- Dim d As Object
- Dim arr, brr
- Dim i As Integer, r As Integer, c As Integer
- Dim rs As Integer, cs As Integer
- Dim k As String
- Dim rng As Range
- Application.ScreenUpdating = False
- Set d = CreateObject("Scripting.Dictionary")
- arr = Sheet2.Range("a1").CurrentRegion '将源数据写入数组
- For i = 2 To UBound(arr) '统计源数据至字典
- k = arr(i, 1) & CLng(arr(i, 3))
- d(k) = d(k) + arr(i, 7)
- Next
- rs = Sheet1.Range("D" & Sheet1.Cells.Rows.Count).End(xlUp).Row
- cs = Sheet1.Range("F1").End(xlToRight).Column
- Set rng = Sheet1.Range(Sheet1.Cells(2, 7), Sheet1.Cells(rs, cs))
- rng.Clear '清除目标区域
- ReDim brr(2 To rs, 7 To cs)
- For r = 2 To rs
- For c = 7 To cs
- k = Cells(r, 3) & CLng(Cells(1, c))
- brr(r, c) = d(k) '先把统计数据写入数组
- Next
- Next
- rng = brr '再写入目标区域。优点是快,缺点是没法跳过小计行,没法为小计行添加公式。
- Set d = Nothing
- Application.ScreenUpdating = True
- End Sub
- Sub 单元格逐个写入()
- Dim d As Object
- Dim arr
- Dim i As Integer, r As Integer, c As Integer
- Dim rs As Integer, cs As Integer
- Dim k As String
- Application.ScreenUpdating = False
- Set d = CreateObject("Scripting.Dictionary")
- arr = Sheet2.Range("a1").CurrentRegion '将源数据写入数组
- For i = 2 To UBound(arr) '统计源数据至字典
- k = arr(i, 1) & CLng(arr(i, 3))
- d(k) = d(k) + arr(i, 7)
- Next
- rs = Sheet1.Range("D" & Sheet1.Cells.Rows.Count).End(xlUp).Row '倒数第二行
- cs = Sheet1.Range("F1").End(xlToRight).Column '最后一列
- Sheet1.Range(Sheet1.Cells(2, 7), Sheet1.Cells(rs, cs)).Clear '清除目标数据
- For r = 2 To rs
- For c = 7 To cs
- If IsEmpty(Sheet1.Cells(r, 3).Value) Then '如果某行的门店号为空,表明该行为小计,需插入求和公式
- Sheet1.Cells(r, c).FormulaR1C1 = "=SUM(R[-" & r - 2 & "]C:R[-1]C)" '如果有多行小计则需要更换判断标准
- Else
- k = Cells(r, 3) & CLng(Cells(1, c))
- Sheet1.Cells(r, c) = d(k) '填入门店统计数据
- End If
- Next
- Next
- Set d = Nothing
- Application.ScreenUpdating = True
- End Sub
复制代码
|
|