我正在尝试在VBA中使用Sumif函数,但是,我遇到了运行时错误。当我尝试将变量CritLastCol添加到公式中时,错误开始了。如果我用实际的单元格引用替换它,它可以工作。我希望能够自动填充此下面的行,我的标准将根据行进行更改。换句话说,我的总和范围和标准范围是固定的,我的标准是我的activecell左边的单元格(但不是一个,可能是20,30列)。
Sub SumBydimcode()
Dim lastCol As Integer
Dim CritLastCol As String
lastCol = Cells(3 & Columns.Count).End(xlToLeft).Column
lastRow = Range("A" & Rows.Count).End(xlUp).Row
NewLastRow = Range("I" & Rows.Count).End(xlUp).Row
CritLastCol = ActiveCell.End(xlToLeft).Value
ActiveCell.FormulaR1C1 = "=SUMIF(R3C8:R" & lastRow & "C8," & CritLastCol & ",R3C10:R" & lastRow & "C" & lastCol & ")"
ActiveCell.AutoFill Destination:=Range(ActiveCell.Address & ":J" & NewLastRow)
End Sub
答案 0 :(得分:0)
您需要在引号中包围CritLastCol
变量。要在VBA中执行此操作,请使用双引号""
。因此,您的代码将如下所示:
ActiveCell.FormulaR1C1 = "=SUMIF(R3C8:R" & lastRow & "C8,""" & CritLastCol & """,R3C10:R" & lastRow & "C" & lastCol & ")"
请注意围绕CritLastCol
答案 1 :(得分:0)
好的,我找到了一种方法来实现它...而不是自动填充,我使用了从数据末尾开始并重新开始工作的循环。
Sub SumBydimcode()
Dim lastCol As Integer
Dim CritLastCol As String
lastCol = Cells(3 & Columns.Count).End(xlToLeft).Column
lastRow = Range("A" & Rows.Count).End(xlUp).Row
NewLastRow = Range("I" & Rows.Count).End(xlUp).Row
NewFirstRow = lastRow + 7
S = ActiveCell.Row
If S > NewLastRow - NewFirstRow Then
For S = ActiveCell.Row To NewFirstRow Step -1
CritLastCol = ActiveCell.End(xlToLeft).Value
ActiveCell.FormulaR1C1 = "=SUMIF(R3C8:R" & lastRow & "C8,""" & CritLastCol & """,R3C10:R" & lastRow & "C" & lastCol & ")"
ActiveCell.Offset(-1, 0).Select
Next S
End If
End Sub