在使用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':类型不匹配”
您是否知道如何使此代码有效?
谢谢
的Fabio
答案 0 :(得分:5)
试试这个
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语句,如上例所示。
答案 1 :(得分:0)
以下是替代方案:
您可以使用Excel OR 功能,如下所示
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"
,以确定条件是否在字母意义上的其他文本之间。 警告:这有时会导致意外结果,因此请务必事先进行测试。
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代码区分大小写。