嘗試發佈的代碼。我假設你的物品描述在'A'列,你的成本在'B'列。它的作用是將一個間接求和放到與它找到的每個'SUB TOTAL'字符串相鄰的'B'列中(鍵入的方式忽略大小寫)。我也假定值從第1行開始,你可能不希望它做。我積累了一個總和字符串,並將其放在最後一個小計行後面的行中。每個小計單元都會被賦予一個青色背景和一個頂部邊框。大概你可以繼續從這一點,並修改它,以滿足您的需求。
Function findSubTotalRows(lastRow As Integer) As Collection
Dim regEx As New RegExp
Dim subTotCols As Collection
regEx.Global = True
regEx.IgnoreCase = True
regEx.Pattern = "^SUB TOTAL$"
Dim row As Integer
Dim val As String
Set subTotCols = New Collection
For row = 1 To lastRow:
val = Trim(Cells(row, 1).Value)
Set mat = regEx.Execute(val)
If mat.Count = 1 Then
subTotCols.Add row
End If
Next
Set findSubTotalRows = subTotCols
End Function
Sub sum_up_subtotals()
Dim lastRow As Integer
Dim cols As Collection
' Find last row in column and all sub total rows
lastRow = Range("A1000").End(xlUp).row
Set cols = findSubTotalRows(lastRow)
Dim prevRow As Integer: prevRow = 0
Dim numRng As Integer
Dim totStr As String: totStr = "=SUM("
For row = 1 To cols.Count:
thisRow = cols(row)
numRng = thisRow - prevRow - 1
With Cells(thisRow, 2)
.Formula = "=SUM(INDIRECT(ADDRESS(ROW()-" & CStr(numRng) & ",COLUMN())&"":""&ADDRESS(ROW()-1,COLUMN())))"
.Interior.Color = vbCyan
.NumberFormat = "$#,##0.00"
.Borders(xlEdgeTop).LineStyle = xlContinuous
End With
prevRow = thisRow
totStr = totStr & "B" & thisRow & ","
Next
totStr = Mid(totStr, 1, Len(totStr) - 1) & ")"
Cells(thisRow + 1, 2).value = totStr
End Sub
關於做這種方式的好處是,你可以插入其他行到每個小計段或添加新的大部段,運行宏,它應該顯示正確的新資金。
它適用於我,但我只是用你提供的數據試過。請注意,您必須啓用正則表達式才能使其工作。
我們真的無法不知道你的代碼的一部分/公式是給你的問題有所幫助。 (除非,或許你的「幫助!」被解釋爲「請別人爲我做這件事,這樣我才能放鬆下來」) – YowE3K
你在推論「幫助」時部分正確。我還沒有寫出正確的編碼。我設置了一個長查找包含「小計」的行,但是我不知道如何編寫範圍,該範圍將讀取兩行之間表示「小計」的值,然後移動到下一行「小計」在裏面。 – gourdblessamerica
IMO最好設置一個變量作爲小計,另一個作爲總數。循環遍歷每一行,並且(1)如果它不是「SUB TOTAL」或「TOTAL」將該行中的值添加到兩個變量,或者(2)如果它是「SUB TOTAL」小計變量,然後將小計變量設置爲零或(3)如果它是「TOTAL」向行寫出總變量。 – YowE3K