VBA 复制数据并对其求和,然后将其粘贴到 NEWSHEET

VBA to copy and SUM the data then paste it into NEWSHEET

我创建了这段代码,它在匹配第 6 行的特定值后复制并粘贴数据,然后将第 7 行数据粘贴到 NewSheet 中。

我无法在 Excel VBA 中创建那个东西。如果“Sheet1”中有多个“总工资”,那么代码将如何对多行的“总工资”求和并将该“SUM”数据粘贴到“NEWSHEET”中。

让我举个例子。

希望创建一个代码,自动对“总工资”行求和并将该求和数据粘贴到“NEWSHEET”中

非常感谢您的帮助。

With ActiveWorkbook.Worksheets("Sheet2")
 Set c = .Rows(6).Find("Q1 2020")
 If Not c Is Nothing Then
.Range(c.Offset(1), c.Offset(1).End(xlToRight)).Copy
ActiveWorkbook.Worksheets("NewSheet").Cells(10, 11).PasteSpecial Paste:=xlPasteValues, Transpose:=True
 End If
 End With

最终结果

请测试下一段代码:

Sub testCopySumQ()
 Dim sh2 As Worksheet, shNS As Worksheet, c As Range
 Dim lastR As Long, lastCol As Long, arrS, strForm As String
 
 Set sh2 = ActiveSheet 'ActiveWorkbook.Worksheets("Sheet2")
 Set shNS = sh2.Next 'Worksheets("NewSheet")
 With sh2
     Set c = .rows(6).Find("Q1 2020")
     If Not c Is Nothing Then
        lastR = .cells(rows.count, c.Column).End(xlUp).row 'last row on the c Column
        lastCol = .cells(c.row, Columns.count).End(xlToLeft).Column 'last col (even with gaps)
        strForm = "=SumIf(" & c.Offset(1, -5).Address & ":" & .cells(lastR, c.Column - 5).Address & _
            ", ""Gross Wage"", " & c.Offset(1).Address(0, 0) & ":" & .cells(lastR, c.Column).Address(0, 0) & ")"
                                                  
        .cells(lastR + 1, c.Column).Formula = strForm  'place the SumIf formula on last empty column cell
        .cells(lastR + 1, c.Column).AutoFill Destination:=.Range(.cells(lastR + 1, c.Column), _
                                            .cells(lastR + 1, lastCol)), Type:=xlFillDefault 'fill the formula to right
        With .Range(.cells(lastR + 1, c.Column), .cells(lastR + 1, lastCol))
            arrS = .Value   'put the value in an array
            .ClearContents  'clear the helper row
        End With
        'drop the array value
        shNS.cells(10, 11).Resize(UBound(arrS), UBound(arrS, 2)).Value = arrS
     End If
 End With
 MsgBox "Ready..."
End Sub

但是您真的需要始终粘贴“K10”单元格吗?或者在“K:K”列的最后一个空单元格中?以防在此列和保留四分之一字符串的列之间插入其他列。

已编辑:

我用于存在“Gross Wage”字符串的列 Offset(1, -5),意思是在将找到“Q1 2020”的列之前的第五列...