我需要将代码的最后一部分应用于所有工作表,并且我的代码应该合并重复的日期并汇总其小计。
我只尝试按F5键到每张纸上。
Sub CaseStudy()
Dim Rng As Range, Dn As Range
Dim nRng As Range
Set Rng = Range(Range("A1"), Range("A" & Rows.Count).End(xlUp))
With CreateObject("scripting.dictionary")
.CompareMode = vbTextCompare
For Each Dn In Rng
If Not .Exists(Dn.Value) Then
.Add Dn.Value, Dn.Offset(, 1)
Else
.Item(Dn.Value).Value = .Item(Dn.Value).Value + Dn.Offset(, 1)
If nRng Is Nothing Then
Set nRng = Dn
Else
Set nRng = Union(nRng, Dn)
End If
End If
Next
If Not nRng Is Nothing Then nRng.EntireRow.Delete
End With
End Sub
我想将代码自动应用于所有工作表。
答案 0 :(得分:1)
“划分和规则”是构建代码的最佳方法之一。因此,将每个工作表作为参数传递给Sub CaseStudy
。
为了获取每个工作表,请遍历工作簿的Worksheets
集合:
Sub ApplyToAllSheets()
Dim wks As Worksheet
For Each wks In ThisWorkbook.Worksheets
CaseStudy wks
Next
End Sub
Sub CaseStudy(wks As Worksheet)
Dim Rng As Range, Dn As Range
Dim nRng As Range
With wks
Set Rng = .Range(.Range("A1"), .Range("A" & .Rows.Count).End(xlUp))
End With
With CreateObject("scripting.dictionary")
.CompareMode = vbTextCompare
For Each Dn In Rng
If Not .Exists(Dn.Value) Then
.Add Dn.Value, Dn.Offset(, 1)
Else
.Item(Dn.Value).Value = .Item(Dn.Value).Value + Dn.Offset(, 1)
If nRng Is Nothing Then
Set nRng = Dn
Else
Set nRng = Union(nRng, Dn)
End If
End If
Next
If Not nRng Is Nothing Then nRng.EntireRow.Delete
End With
End Sub