excel - VBA 复制和求和数据,然后将其粘贴到 NEWSHEET
问题描述
我创建了这段代码,它在匹配第 6 行的特定值后复制并粘贴数据,然后将第 7 行数据粘贴到 NewSheet 中。
我无法在 Excel VBA 中创建那个东西。如果“Sheet1”中有多个“总工资”,那么代码将如何对多行中的“总工资”求和并将“总和”数据粘贴到“新闻表”中。
希望创建一个代码,该代码将自动对“总工资”行进行求和并将该 SUM 数据粘贴到“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”的列之前的第五列...
推荐阅读
- sql - 在滚动两周内查找唯一计数
- mongodb - 如何使用另一个字段的值更新 MongoDB 字段
- java - Java ConcurrentHashMap 初始化
- node.js - 如何使用 bootstrap-vue 上传多个文件
- c# - 使用 CefSharp 将 HTML 转为 PDF
- animation - 如何使用 GNU Octave 制作移动点阵的动画
- javascript - 无法为 Vega-Lite 设置宽度和高度
- qt - 单击QTabWidget的cornerWidget后如何将焦点设置回当前选项卡小部件?
- reactjs - Rechart Legend 掩盖了 Mobile 中的图表
- r - r 按组求和矩阵