Попробуйте этот код.Предполагается, что ваш итог находится в столбце X.
Sub Macro1()
Dim EmptyFields As Integer
Dim MyRow As Integer
Dim GrandTotal As Integer
Dim Percent1, Percent2, Percent3 As Double
EmptyFields = 0
MyRow = 1
' if 3 continuous cells are empty, we should assume that the dataset is over
Do While EmptyFields < 3
Range("X" & MyRow).Select
' if we see Total in column X, we should get grand total of that row
' and caculate percentages. Then, we add a new row below it
' and store the percentages in the new row
If LCase(Range("X" & MyRow).Text) = "total" Then
GrandTotal = Range("Y" & MyRow).Value + Range("Z" & MyRow).Value + Range("AA" & MyRow).Value
Percent1 = Round(Range("Y" & MyRow).Value * 100 / GrandTotal)
Percent2 = Round(Range("Z" & MyRow).Value * 100 / GrandTotal)
Percent3 = Round(Range("AA" & MyRow).Value * 100 / GrandTotal)
Range("X" & MyRow + 1).Select
Selection.EntireRow.Insert , copyorigin:=xlFormatFromLeftOrAbove
Range("X" & MyRow + 1).Select
ActiveCell.FormulaR1C1 = "Percent"
Range("Y" & MyRow + 1).Select
ActiveCell.FormulaR1C1 = Str(Percent1) & "%"
Range("Z" & MyRow + 1).Select
ActiveCell.FormulaR1C1 = Str(Percent2) & "%"
Range("AA" & MyRow + 1).Select
ActiveCell.FormulaR1C1 = Str(Percent3) & "%"
EmptyFields = 0
MyRow = MyRow + 1
' if cell is empty, increment empty fields variable
ElseIf Len(Trim(Range("X" & MyRow).Text)) = 0 Then
EmptyFields = EmptyFields + 1
Else
EmptyFields = 0
End If
MyRow = MyRow + 1
Loop
End Sub
На основе обновленного требования попробуйте этот код:
Sub Macro1()
Dim EmptyFields, MyRow, GrandTotal As Integer
Dim Percent1, Percent2, Percent3 As Double
Dim TotalLabel As String
EmptyFields = 0
MyRow = 1
' if 3 continuous cells are empty, we should assume that the dataset is over
Do While EmptyFields < 3
Range("Q" & MyRow).Select
TotalLabel = Range("Q" & MyRow).Text
' if we see Total in column X, we should get grand total of that row
' and caculate percentages. Then, we add a new row below it
' and store the percentages in the new row
If InStr(LCase(TotalLabel), "total") > 0 Then
GrandTotal = Range("Y" & MyRow).Value + Range("Z" & MyRow).Value + Range("AA" & MyRow).Value
Percent1 = Round(Range("Y" & MyRow).Value * 100 / GrandTotal)
Percent2 = Round(Range("Z" & MyRow).Value * 100 / GrandTotal)
Percent3 = Round(Range("AA" & MyRow).Value * 100 / GrandTotal)
Range("Q" & MyRow + 1).Select
Selection.EntireRow.Insert , copyorigin:=xlFormatFromLeftOrAbove
Range("Q" & MyRow + 1).Select
ActiveCell.FormulaR1C1 = Replace(LCase(TotalLabel), "total", "Percent")
Range("Y" & MyRow + 1).Select
ActiveCell.FormulaR1C1 = Str(Percent1) & "%"
Range("Z" & MyRow + 1).Select
ActiveCell.FormulaR1C1 = Str(Percent2) & "%"
Range("AA" & MyRow + 1).Select
ActiveCell.FormulaR1C1 = Str(Percent3) & "%"
EmptyFields = 0
MyRow = MyRow + 1
' if cell is empty, increment empty fields variable
ElseIf Len(Trim(Range("Q" & MyRow).Text)) = 0 Then
EmptyFields = EmptyFields + 1
Else
EmptyFields = 0
End If
MyRow = MyRow + 1
Loop
End Sub