简体   繁体   English

在VBA中使用变量的公式

[英]Formula using Variables with VBA

I am wrestling with the syntax of this one line of some code. 我正在努力处理这一行代码的语法。 the formula with "IfError" seems to have the wrong syntax. 具有“ IfError”的公式的语法似乎错误。 I believe I have the quotes in the right places. 我相信我在正确的地方引用了报价。

    Dim j As Integer
    Dim MidPointE As String
    Dim Dist As String
    Dim Allocation As String

    MidPointE = "AM"
    Dist = "AN"
    Allocation = "AO"

   for J= 1 to 300
     Cells(j, Dist).Formula = "=IFERROR(" & MidPointE & j & " / " & MidPointE &  CustomerLast & ", "")"
    Cells(j, Allocation).Formula = "=" & Allocation & j & "* S" & CustomerLast

     Next J

Try this : 试试这个

 Cells(j, Dist).Formula = "=IFERROR(" & MidPointE & j & " / " & MidPointE &  CustomerLast & ", """")"

Quotes inside a string literal must be escaped - and that's done by doubling them up. 字符串文字中的引号必须转义-通过将它们加倍来完成。

You can also assign multiple formulas at the same time: 您还可以同时分配多个公式:

Range("AN1:AN300").Formula = "=IFERROR(AM1 / AM$" &  CustomerLast & ", """")"
Range("AO1:AO300").Formula = "=AO1 * S$" & CustomerLast

I also recommend looking into Excel Tables and Structured References 我也建议研究Excel表格和结构化引用

To avoid the circular reference issue, you can calculate the formulas and assign the values directly: 为了避免循环引用问题,您可以计算公式并直接分配值:

Range("AN1:AN300") = Evaluate("IFERROR(AM1:AM300 / AM$" &  CustomerLast & ", """")")
Range("AO1:AO300") = Evaluate("INDEX(AO1:AO300 * S$" & CustomerLast & ",)")

It's at the end here 在这里结束

& ", "")"

The two quotes between the comma and ) end the string and start a new one. 逗号和)之间的两个引号使字符串结尾并开始一个新的引号。

'first string
","

'second string
")"

Since you can't just throw two strings together like that, i would replace the two quotes with the CHR equivalent. 由于您不能像这样将两个字符串扔在一起,因此我将用CHR等效项替换两个引号。 Should look something like this: 应该看起来像这样:

Cells(j, Dist).Formula = "=IFERROR(" & MidPointE & j & " / " & MidPointE &  CustomerLast & ", "& CHR(034) & CHR(034) & ")"
'pretty sure 034 is the ascii code for "

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM