在另一列Excel VBA中过滤后的列值总和,可以通过以下步骤实现:
Dim xlApp As Excel.Application
Dim xlWorkbook As Excel.Workbook
Dim xlWorksheet As Excel.Worksheet
Set xlApp = New Excel.Application
Set xlWorkbook = xlApp.Workbooks.Open("路径\文件名.xlsx")
Set xlWorksheet = xlWorkbook.Worksheets("工作表名")
Dim filterRange As Range
Dim filteredRange As Range
Dim sumRange As Range
Set filterRange = xlWorksheet.Range("A1:A10") '设置要过滤的列范围
Set filteredRange = filterRange.SpecialCells(xlCellTypeVisible) '过滤后的可见单元格范围
Set sumRange = xlWorksheet.Range("B1:B10") '设置要求和的列范围
filterRange.AutoFilter Field:=1, Criteria1:="过滤条件"
请将"过滤条件"替换为实际的过滤条件。
Dim sumValue As Double
sumValue = Application.WorksheetFunction.Sum(filteredRange.Offset(0, 1)) '计算过滤后列值的总和
这将计算过滤后列值的总和,并将结果存储在sumValue变量中。
xlWorkbook.Close SaveChanges:=False
xlApp.Quit
Set xlWorksheet = Nothing
Set xlWorkbook = Nothing
Set xlApp = Nothing
完整的VBA代码如下所示:
Sub CalculateFilteredColumnSum()
Dim xlApp As Excel.Application
Dim xlWorkbook As Excel.Workbook
Dim xlWorksheet As Excel.Worksheet
Dim filterRange As Range
Dim filteredRange As Range
Dim sumRange As Range
Dim sumValue As Double
Set xlApp = New Excel.Application
Set xlWorkbook = xlApp.Workbooks.Open("路径\文件名.xlsx")
Set xlWorksheet = xlWorkbook.Worksheets("工作表名")
Set filterRange = xlWorksheet.Range("A1:A10")
Set filteredRange = filterRange.SpecialCells(xlCellTypeVisible)
Set sumRange = xlWorksheet.Range("B1:B10")
filterRange.AutoFilter Field:=1, Criteria1:="过滤条件"
sumValue = Application.WorksheetFunction.Sum(filteredRange.Offset(0, 1))
xlWorkbook.Close SaveChanges:=False
xlApp.Quit
Set xlWorksheet = Nothing
Set xlWorkbook = Nothing
Set xlApp = Nothing
MsgBox "过滤后列值的总和为: " & sumValue
End Sub
请将"路径\文件名.xlsx"替换为实际的Excel文件路径和文件名,将"工作表名"替换为实际的工作表名称,将"过滤条件"替换为实际的过滤条件。
这样,当运行该VBA宏时,将计算过滤后列值的总和,并通过消息框显示结果。
领取专属 10元无门槛券
手把手带您无忧上云