vba 中带有 RC 的 IF 语句会出现编译错误,为什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21077627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 01:21:49  来源:igfitidea点击:

IF statement with RC in vba gives compile error, why?

excelvbaexcel-vbaif-statement

提问by SteewDK

I am currently working on a small VBA code that needs to compare a piece of string. If I would type this directly into excel I would do following:

我目前正在编写一个需要比较一段字符串的小型 VBA 代码。如果我将其直接输入到 excel 中,我将执行以下操作:

=IF(C14 = "ABC",1,0)

Now, since this is a VBA code, it needs to do this as a relative reference. Instead it would look something like this:

现在,由于这是一个 VBA 代码,因此需要将其作为相对引用来执行。相反,它看起来像这样:

=IF(RC[-5] = "ABC",1,0)

Problem: Now, the latter IFstatement gives a compile error - why so?

问题:现在,后IF一条语句给出了编译错误 - 为什么会这样?

If I where to type in

如果我在哪里输入

  =IF(RC[-5] = 2,1,0)

This does not give any compile error. So it appears that the String comparisment gives me problems.

这不会给出任何编译错误。所以看起来字符串比较给我带来了问题。

采纳答案by Siddharth Rout

For vba code try this

对于 vba 代码试试这个

ActiveCell.FormulaR1C1 = "=IF(RC[-5]=""ABC"",1,0)"

Followup from comments.

从评论跟进。

Howcome the double "" is needed? – SteewDK 3 mins ago

为什么需要双“”?– SteewDK 3 分钟前

We need the extra "to encompass the double quotes to pass it as a string. You could use Chr(34)as well. For example

我们需要额外的东西"来包含双引号以将其作为字符串传递。你也可以使用Chr(34)。例如

ActiveCell.FormulaR1C1 = "=IF(RC[-5]=" & Chr(34) & "ABC" & Chr(34) & ",1,0)"

BTW if you do not want to use a formula then you can use OFFSETas well

顺便说一句,如果你不希望使用一个公式,那么你可以使用OFFSET,以及

For example

例如

If ActiveCell.Offset(0,-5).Value = "ABC" Then _
ActiveCell.Value = 1 Else ActiveCell.Value = 0