'假设明细表A列有序,另外明细表中的城市名工作表都已存在,自己修改
Option Explicit
Sub test()
Dim arr, i, j, k, m, sum, brr
arr = Sheets("明细表").[a5].CurrentRegion.Offset(1)
brr = arr
For i = 1 To UBound(arr, 1) - 1
If Len(arr(i, 9)) = 0 Then
m = m + 1: sum = sum + arr(i, 7)
For j = 1 To UBound(arr, 2): brr(m, j) = arr(i, j): Next
End If
If arr(i + 1, 1) <> arr(i, 1) Then
For j = 1 To UBound(arr, 1) - 1
If InStr(arr(j, 9), arr(i, 1)) Then
m = m + 1: sum = sum + arr(j, 7)
For k = 1 To UBound(arr, 2): brr(m, k) = arr(j, k): Next
End If
Next
With Sheets(arr(i, 1)).[a5]
.Resize(Rows.Count - 4, UBound(brr, 2)).ClearContents
If m > 0 Then
.Resize(m, UBound(brr, 2)) = brr
.Cells(m + 2, 1) = "合计"
.Cells(m + 2, 7) = sum
End If
End With
m = 0: sum = 0
End If
Next
End Sub |