如何使用excel vba获得具有相同代码(条件)的行总和

时间:2018-01-30 09:34:21

标签: excel excel-vba vba

我在表1中有很多数据示例:列A:代码,列B:日期,...列AK:金额。 我需要一个宏,例如可以选择所有相同的代码并将数量相加并将其放在sheet2的范围(G22)上。 我试过了,但它不起作用:

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

1 个答案:

答案 0 :(得分:0)

以下内容如何:

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