我是VBA的新手,试图弄清楚这一点,我还没有使用函数。我正在尝试在VBA工作表上自动执行SUMIF公式。记录表将包含动态SUMIF公式,该公式基于D列中基于B列值的变量/范围。 SUM范围将来自CB表,匹配列K和求和列L。以下代码不为SUMIF函数返回任何值,也没有要报告的错误。
下图中的数据样本:
https://i.stack.imgur.com/VvDfw.png
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim ws As Worksheet
Dim NoCol As Integer, NoRow As Integer
Dim CritRng As Range, SumRng As Range
Application.ScreenUpdating = False
Set ws = Worksheets("Rec")
With ws
NoRow = .Cells(.Cells.Rows.Count, 3).End(xlUp).Row
NoCol = .Cells(3, .Cells.Columns.Count).End(xlToLeft).Column
Set CritRng = Sheets("CB").Range("k:k")
Set SumRng = Sheets("CB").Range("L:L")
End With
For r = 3 To NoRow
Cells(r, NoCol) = WorksheetFunction.SumIf(CritRng, Cells(r, 1), SumRng)
Next r
Application.ScreenUpdating = True
End Sub
```
1。如何使用SUMIF函数
我建议您始终使用SUMIFS函数,它更灵活,因为它允许您有多个条件
根据documentation,SUMIF函数的语法为:
expression.SumIfs (Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9, Arg10, Arg11, Arg12, Arg13, Arg14, Arg15, Arg16, Arg17, Arg18, Arg19, Arg20, Arg21, Arg22, Arg23, Arg24, Arg25, Arg26, Arg27, Arg28, Arg29, Arg30)
位置:
[Arg1
是Range
的类型,对应于Sum_range - the range to sum
[Arg2
是Range
的类型,对应于Criteria_range1, criteria_range2... - One or more ranges in which to evaluate the associated criteria
[Arg3 - Arg30
是Variant
的类型,对应于Criteria1, criteria2... - One or more criteria in the form of a number, expression, cell reference, or text that define which cells will be added
2。关于您的代码
您想使用与Change
不同的SelectionChange
事件
[第一个在更改cell
或range
时触发,第二个在您使用鼠标,键盘或其他VBA代码更改选择时触发。
使用更改事件
Private Sub Worksheet_Change(ByVal Target As Range)
Dim monitoredRange As Range
Dim cell As Range
Dim sumRange As Range
Dim criteriaRange As Range
Dim sumOffsetColumn As Long
Dim sumFirstRow As Long
Dim sumLastRow As Long
' Initialize variables
sumOffsetColumn = 2 ' How many columns offset from the Target (changed) cell
sumFirstRow = 4
sumLastRow = 1000
Set monitoredRange = Me.Range("B:B") ' Here you can restrict this to a certain row
' Check if changed cell/range is not in the monitored range exit the procedure
If Intersect(Target, monitoredRange) Is Nothing Then Exit Sub
' Set the sumifs parameters
Set sumRange = Sheet1.Range("L" & sumFirstRow & ":L" & sumLastRow) ' Use sheet's codename (Sheet1)
Set citeriaRange = Sheet1.Range("K" & sumFirstRow & ":K" & sumLastRow) ' Use sheet's codename (Sheet1)
' Apply to each cell in target range
For Each cell In Target.Cells
' Check that the cell is not null
If cell.Value <> vbNullString Then
' Set the value to the conditional sum
cell.Offset(0, sumOffsetColumn).Value = Application.WorksheetFunction.SumIfs(sumRange, citeriaRange, cell.Value)
End If
Next cell
End Sub
3。 Excel(结构化)表方法
[我经常看到人们尝试使用VBA
重新发明轮子。在很多情况下,您不需要编写解决方案的代码,因为Excel团队已将功能合并到程序本身中。
在这种情况下,您可以使用Excel Tables
收件人
6。将以下公式添加到SUM列的第一个单元格中
=SUMIFS(CB!L:L;CB!K:K;[@[Account '#]])
让我知道是否可行