回答編集履歴

2

サンプルコード追記

2025/04/24 14:52

投稿

hatena19
hatena19

スコア34352

test CHANGED
@@ -93,4 +93,43 @@
93
93
  End Sub
94
94
  ```
95
95
 
96
+ ---
97
+ > Excelの関数でしたら実現できると思うのですが、該当する行が変わるので、その都度入力する手間もかかるため、VBAで実現できないかと考えています。
96
98
 
99
+ VBAで集計関数(SUMIF)を使った数式を生成してセルに代入するサンプルコードも置いておきます。
100
+
101
+ ```vba
102
+ Public Sub SetSumFormula()
103
+ Dim ws As Worksheet
104
+ Set ws = ThisWorkbook.Sheets("収益状況")
105
+
106
+ Dim LastRow As Long ' A列の最終行
107
+ LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
108
+
109
+ Dim SumCells As Range ' 集計セル
110
+ Set SumCells = ws.Range("L1:N1,R1:U1,X1:AD1,AH1:AV1")
111
+
112
+ Const conFormula = "=SUMIF($B#1:$B#2,""*合計*"",L#1:L#2)" '集計数式テンプレート, #1=集計開始行,#2=集計最終行
113
+
114
+ Application.Calculation = xlCalculationManual
115
+
116
+ Dim beginRow As Long '集計開始行
117
+ beginRow = 6
118
+ Dim currentRow As Long
119
+ For currentRow = 6 To LastRow
120
+ If ws.Cells(currentRow, "A").Value Like "*合計*" Then
121
+ With SumCells.Offset(currentRow - 1)
122
+ .Value = Replace(Replace(conFormula, "#1", beginRow), "#2", currentRow - 1)
123
+ End With
124
+ beginRow = currentRow + 1
125
+ End If
126
+ Next currentRow
127
+
128
+ Application.Calculation = xlCalculationAutomatic
129
+
130
+ MsgBox "指定された列に順次集計式を設定しました!", vbInformation
131
+ End Sub
132
+ ```
133
+
134
+
135
+

1

コードのミスを修正

2025/04/23 03:25

投稿

hatena19
hatena19

スコア34352

test CHANGED
@@ -65,7 +65,7 @@
65
65
 
66
66
  ' 合計する列を指定
67
67
  sumColumns = Array(12, 13, 14, 18, 19, 20, 21, 24, 25, 26, 27, 28, 29, 30, _
68
- '34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48)
68
+ 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48)
69
69
  ' 各列の合計値を格納する配列を初期化
70
70
  ReDim totalSums(UBound(sumColumns))
71
71