在vba中添加公式 - 语法错误

时间:2016-12-07 06:55:22

标签: excel vba excel-vba

我试图录制一个宏。我在excel中的公式是:

=IF(AND(OR(B2={"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15 ","16 "}),OR(J2={"Q1","Q2","Q3","Q4"})),CONCATENATE(J2," ",IF(K2="p","pre",""),"-"," ",IF(A2="",0,A2)),"")

(这个公式基本上根据季度和类型更改了我的产品名称,同时考虑了前几个季度)

注意:一旦我录制它。在vba中看起来像这样:

Selection.FormulaR1C1 = _ "=IF(AND(OR(RC[-6]={""1"",""2"",""3"",""4"",""5"",""6"",""7"",""8"",""9"",""10"",""11"",""12"",""13"",""14"",""15 "",""16 ""}),OR(RC[2]={""Q1"",""Q2"",""Q3"",""Q4""})),CONCATENATE(RC[2],"" "",IF(RC[3]=""p"",""pre"",""""),""-"","" "",IF("& _ """",0,RC[-7])),"""")"

然而,它给了我一个语法错误......什么错了?!

谢谢

2 个答案:

答案 0 :(得分:0)

唯一错误的是"& _部分。它应该由RC[-7]=替换。请参阅下面的更正行。

Selection.FormulaR1C1 = _
        "=IF(AND(OR(RC[-6]={""1"",""2"",""3"",""4"",""5"",""6"",""7"",""8"",""9"",""10"",""11"",""12"",""13"",""14"",""15 "",""16 ""}), OR(RC[2]={""Q1"",""Q2"",""Q3"",""Q4""})), CONCATENATE(RC[2],"" "",IF(RC[3]=""p"",""pre"",""""),""-"","" "",IF(RC[-7]="""",0,RC[-7])),"""")"

答案 1 :(得分:0)

IF(A2="",0,A2)),"")正在转换为IF(""",0,RC[-7])),"""")

假设您的原始公式位于Range("H2")

"=IF(AND(OR(RC[-6]={""1"",""2"",""3"",""4"",""5"",""6"",""7"",""8"",""9"",""10"",""11"",""12"",""13"",""14"",""15 "",""16 ""}),OR(RC[2]={""Q1"",""Q2"",""Q3"",""Q4""})),CONCATENATE(RC[2],"" "",IF(RC[3]=""p"",""pre"",""""),""-"","" "",IF(RC[-7]="""",0,RC[-7])),"""")"

使用配方容量

时,我不认为需要用引号括起数字
"=IF(AND(OR(RC[-6]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}),OR(RC[2]={""Q1"",""Q2"",""Q3"",""Q4""})),CONCATENATE(RC[2],"" "",IF(RC[3]=""p"",""pre"",""""),""-"","" "",IF(RC[-7]="""",0,RC[-7])),"""")"

不要在双转义模式""""的中间开始续行。我希望在可能的情况下将它们置于语句之间

将公式转换为R1C1表示法的最简单方法是使用立即窗口

  

?Chr(34)&替换(范围(“H2”)。FormulaR1C1,chr(34),Chr(34)& Chr(34))& CHR(34)

enter image description here

尽可能在立即窗口中构建和测试字符串。当它出错时会抱怨

enter image description here

在编写连接时,您甚至可以在立即窗口中使用创建变量

enter image description here