运行时错误“13”:IF与IF语句结合的types不匹配

在我使用excel的VBA代码中

Dim Field2 As String Field2 = Cells(i, 4).Value If Right(Field2, 3) = ("A-1" Or "A-2" Or "B-1" Or "B-2" Or "C-1" Or "C-2" Or "D-1" Or "D-2" Or "D-3") Then Cells(i, 50).Value = "OtherPrtnrs /Dcrs & Dept heads" End If 

当我运行代码时,我收到以下消息:“运行时错误13”:types不匹配“

你有什么想法如何使这个代码工作?

谢谢

法比奥

尝试这个

 If Right(Field2, 3) = "A-1" Or _ Right(Field2, 3) = "A-2" Or _ Right(Field2, 3) = "B-1" Or _ Right(Field2, 3) = "B-2" Or _ Right(Field2, 3) = "C-1" Or _ Right(Field2, 3) = "C-2" Or _ Right(Field2, 3) = "D-1" Or _ Right(Field2, 3) = "D-2" Or _ Right(Field2, 3) = "D-3" Then Cells(i, 50).Value = "OtherPrtnrs /Dcrs & Dept heads" End If 

还是更好的…这个

 Select Case Right(Field2, 3) Case "A-1","A-2","B-1","B-2","C-1","C-2","D-1","D-2","D-3" Cells(i, 50).Value = "OtherPrtnrs /Dcrs & Dept heads" End Select 

:我假设i是一个有效的行号

说明

比较使用If语句时,不能说If A = B or C 你应该比较是分开的。 If A = B or A = C Then 。 这里每个OR是它自己的Boolean语句,即它将被分开评估。

当你有多个这样的比较时,最好使用一个Select语句,如上例所示。

以下是替代scheme:

您可以使用Excel ORfunction如下

 Dim Str As String, ChkStr As Boolean Field2 = Cells(i, 4) Str = Right(Field2, 3) ChkStr = WorksheetFunction.Or(Str = "A-1", Str = "A-2", Str = "B-1", Str = "B-2", Str = "C-1", _ Str = "C-2", Str = "D-1", Str = "D-2", Str = "D-3") If ChkStr Then 'Alternatively: If ChkStr = True Then Cells(i, 50) = "OtherPrtnrs /Dcrs & Dept heads" End If 

或者与Siddharth Rout使用Select Case语句对文本特别是"D-1""D-2""D-3"的好处的答案略有不同,以确定条件是否位于其他文本之间在字母意义上。 警告:这可能会导致意外的结果,因此请确保您事先进行testing。

 Select Case Right(Field2, 3) Case "A-1" To "A-2", "B-1" To "B-2", "C-1" To "C-2", "D-1" To "D-3" Cells(i, 50) = "OtherPrtnrs /Dcrs & Dept heads" End Select 

最后但并非最不重要的是使用For Each … Next语句的数组

 StrList = Array("A-1", "A-2", "B-1", "B-2", "C-1", "C-2", "D-1", "D-2", "D-3") For Each element In StrList If Right(Field2, 3) = element Then Cells(i, 50) = "OtherPrtnrs /Dcrs & Dept heads" Exit For End If Next 

这里应该做的一点是,默认情况下,VBA代码是区分大小写的。