简体   繁体   English

如何使用Excel VBA具有相同代码(条件)的行总和

[英]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. 我在工作表1示例中有许多数据:A列:代码,B列:日期,... AK列:金额。 I need a macro that for example can select all same code and sum there amount and put it on range(G22) of sheet2. 我需要一个宏,例如可以选择所有相同的代码并将其总和添加到sheet2的range(G22)上。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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