|
VBAを勉強し始めたばかりの初心者です。
sheet1の売り上げデータを元に、sheet2(sheet2とはタブが別のシート)の店と商品ごとの売り上げ集計をしたい。といった問題です。
模範解答はこちらです。
Sub 練習問題15()
Dim i As Long
Dim ixR As Long
Dim ixC As Long
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set ws1 = Worksheets("練習15")
Set ws2 = Worksheets("練習15_回答")
ws2.Range("A1").CurrentRegion.Offset(1, 1).ClearContents
With ws1
For i = 2 To .Cells(.Rows.Count, 1).End(xlUp).Row
ixC = 2
Do Until ws2.Cells(1, ixC) = .Cells(i, 1)
ixC = ixC + 1
Loop
ixR = 2
Do Until ws2.Cells(ixR, 1) = .Cells(i, 2)
ixR = ixR + 1
Loop
ws2.Cells(ixR, ixC) = ws2.Cells(ixR, ixC) + .Cells(i, 3)
Next
End With
End Sub
do loop の無限ループを防ぎたく、for nextとsumifsを使って作りたいのですが、作り方がわかりません。
どなたかご教示いただきたくお願いいたします。
ちなみにこちらがsumifsで自分なりに作ったVBAです。当然起動しませんでした。
Sub 練習問題15()
Application.ScreenUpdating = False
Dim i As Long
Dim j As Long
Dim ws2Row As Long
Dim ws2column As Long
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set ws1 = Worksheets("練習15")
Set ws2 = Worksheets("練習15_回答")
ws2.Range("A1").CurrentRegion.Offset(1, 1).ClearContents
With ws1
For i = 2 To .Cells(Rows.Count, 1).End(xlUp).Row
For j = 1 To 3
With ws2
For ws2Row = 2 To .Cells(Rows.Count, 1).End(xlUp).Row
For ws2column = 2 To 5
.Cells(ws2Row, ws2column).Value = Application.WorksheetFunction.
SumIfs(.Range("C1", Cells(i, 3)), .Range("A1", Cells(i, 1)), Cells(1, ws2column), .Range("B1", Cells(i, 2)), Cells(ws2Row, 1))
Next
End With
End With
End Sub
|
|