简体   繁体   中英

How can I have the sum of rows with the same code (condition) using excel vba

I have many data on sheet 1 example: column A : code, column B : date, ...column AK: amount. I need a macro that for example can select all same code and sum there amount and put it on range(G22) of sheet2. I tried that but it doesn't work:

Sub BTester()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim ws3 As Worksheet
Dim table1 As Range
Dim table2 As Range
Set ws1 = Worksheets("Feuil1")
Set ws2 = Worksheets("Feuil2")
Set table1 = ws1.Cells
Dim table1Rows As Integer
Dim table1Cols As Integer
table1Rows = ws1.UsedRange.Rows.Count
table2Rows = ws2.UsedRange.Rows.Count

'Boucle1:AACMPMHRO
Dim r As Range, v As Variant
For i = 0 To table1Rows
If ws1.Cells(1 + i, 11) = "AACMPMHRO" Then
'Set r = ws1.Cells(1 + i, 27)
v = Application.ws2Function.Sum("AK1:AK2000").Value

ws2.Range("G22").Value = v
'ws1.Cells(1 + i, 27).Copy ws2.Range("G22")
End If
Next i
'Boucle1:XSUPMONCT
'For i = 1 To table1Rows
'If ws1.Cells(3 + i, 19) = "XSUPMONCT" Then
'ws1.Cells(3 + i, 22).Copy ws2.Range("G23")
'End If
'Next i
'Boucle1:ATITSEEBC
'For i = 1 To table1Rows
'If ws1.Cells(3 + i, 19) = "ATITSEEBC" Then
'ws1.Cells(3 + i, 22).Copy ws2.Range("G26")
'End If
'Next i



End Sub

How about the following:

Sub BTester()
Dim ws1 As Worksheet: Set ws1 = Worksheets("Feuil1")
Dim ws2 As Worksheet: Set ws2 = Worksheets("Feuil2")
Dim LastRow As Long
LastRow = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row

For i = 1 To LastRow
    If ws1.Cells(i, 1) = "AACMPMHRO" Then 'check for code on column 1, amend as required
        v = v + ws1.Cells(i, 37) 'add values from column AK = 37
    End If
Next i
ws2.Range("G22").Value = v
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM