【问题标题】:Run Time Error 1004 SumIf function运行时错误 1004 SumIf 函数
【发布时间】:2014-10-02 21:09:34
【问题描述】:

我正在尝试在 VBA 中使用 Sumif 函数,但是,我遇到了运行时错误。当我尝试将变量 CritLastCol 添加到公式中时,错误开始了。如果我用实际的单元格引用替换它,它就可以工作。我希望能够自动填充下面的行,我的标准将根据行而改变。换句话说,我的总和范围和条件范围是固定的,我的条件是我的活动单元格左侧的单元格(但不是一个,可能是 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

【问题讨论】:

  • 你能在CritLastCol 中输入一个有效的值吗?使用CritLastCol = "WhatYouWant" 进行测试

标签: excel vba


【解决方案1】:

您需要将 CritLastCol 变量括在引号中。要在 VBA 中执行此操作,请使用双引号 "" 两次。因此,您的代码将如下所示:

ActiveCell.FormulaR1C1 = "=SUMIF(R3C8:R" & lastRow & "C8,""" & CritLastCol & """,R3C10:R" & lastRow & "C" & lastCol & ")"

注意CritLastCol 周围的额外双引号

【讨论】:

  • 我的 CritLastCol 随每一行而变化。因此,当我添加额外的双引号时,它会在我想要的列中提取值,但是当我自动填充时它会保持该值,但我希望它改为在下一列中提取标准。
【解决方案2】:

好的,我想出了一个办法……我没有使用自动填充,而是使用了一个从数据末尾开始的循环并进行备份。

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

【讨论】:

    猜你喜欢
    • 2015-02-01
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 2017-12-14
    相关资源
    最近更新 更多