【问题标题】:How to use excel ranges in excel vba formulas如何在excel vba公式中使用excel范围
【发布时间】:2017-04-24 13:40:51
【问题描述】:

使用 Excel VBA 时,我在尝试选项 1 和选项 2 时收到语法错误消息。

如何正确设置范围,以便可以在选项 1 中使用我的公式?

对于选项 2,为什么我不能像在普通 excel 公式中那样引用范围?

这是因为我想将此公式应用于此单元格下方的许多行。我使用 for 循环吗?

默认代码是正确的。

'Default
Range("I2").Formula = "=+SUMIFS(R2C2:R434C2,R2C1:R434C1,RC[-1],R2C3:R434C3,""G"")"

'Option 1
    Dim MyRange As Range
    Set MyRange = Range("B2:B434")
    Range("I2").Formula = _
        "=+SUMIFS(" & MyRange & ",R2C1:R434C1,RC[-1],R2C3:R434C3,""G"")"

'Option 2
    Range("I2").Formula = _
        "=+SUMIFS($B$2:$b$434,R2C1:R434C1,RC[-1],R2C3:R434C3,""G"")"

【问题讨论】:

  • @user3598756 的回答显示了要使用的正确语法。 (请注意,选项 2 与您的默认选项相同,但正确使用 FormulaR1C1 属性而不是强制 Excel 故障转移到它。)您的选项 2 不起作用(我认为)因为您试图混合引用方法在一个公式中。

标签: vba excel


【解决方案1】:
'Default

Range("I2").Formula = "=+SUMIFS(R2C2:R434C2,R2C1:R434C1,RC[-1],R2C3:R434C3,""G"")"

'Option 1

Dim MyRange As Range
Set MyRange = Range("B2:B434")
Range("I2").FormulaR1C1= _
    "=+SUMIFS(" & MyRange.Address(False,False,xlR1C1) & ",R2C1:R434C1,RC[-1],R2C3:R434C3,""G"")"

'Option 2

Range("I2").FormulaR1C1 = _
    "=+SUMIFS(R2C2:R434C2,R2C1:R434C1,RC[-1],R2C3:R434C3,""G"")"

【讨论】:

  • @YowE3K 我尝试了选项 1,但又应用了一个范围。但这对我不起作用。
  • Option 1 Dim irow As Long irow = Application.WorksheetFunction.Match("No Number", Range("A:A"), 0) - 2 Dim MyRange As Range Dim haha As String haha = "B2:B" & irow + 1 Set MyRange = Range(haha) Dim MyRange1 As Range Dim haha1 As String haha1 = "A2:A" & irow + 1 Set MyRange1 = Range(haha1) Range("I2").Formula = _ "=+SUMIFS(" & MyRange.Address(True, True, xlR1C1) & "," & MyRange1.Address(True, True, xlR1C1) & ",R2C3:R434C3,""G"")"
  • @koky - 在您评论中的代码中,您的SUMIFS 的格式似乎是SUMIFS(sum_range,criteria_range1,criteria_range2,criteria2),即您似乎缺少criteria1。 (并且请在使用 R1C1 样式公式时使用 FormulaR1C1 属性 - 这将降低将来出现其他问题的风险。)
  • @YowE3K 感谢您的指出!因此,对于 excel vba,建议使用 FormulaR1C1 进行单元格引用。正常的excel引用不能在excel vba中使用吧。
  • @koky - 如果您使用普通符号在 VBA 中编写公式,请使用 .Formula 属性。如果您使用 R1C1 表示法在 VBA 中编写公式,请使用 .FormulaR1C1 属性。 R1C1 表示法 往往 在 VBA 中更容易(因为说 RC[-4] 比计算当前行是什么以及列字母是什么是剩下的 4 列要容易得多当前专栏),但这实际上取决于您在做什么。 (重要的是,不要试图在一个公式中混合使用两种符号。我见过很多人都遇到过这样的问题。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多