Vba 运行时错误“13”:如果与OR语句组合,则上的类型不匹配
在使用excel的VBA代码中Vba 运行时错误“13”:如果与OR语句组合,则上的类型不匹配,vba,excel,Vba,Excel,在使用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 当
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”:类型不匹配
你知道如何让这个代码工作吗
多谢各位
法比奥试试这个
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
注意:我假设我是一个有效的行号
说明:
当使用If语句进行比较时,不能说A=B还是C。应该单独进行比较。如果A=B或A=C,则。这里,每个OR都是它自己的布尔语句,也就是说,它将被单独计算
当您有多个这样的比较时,最好使用上面示例中所示的Select语句。以下是备选方案: 您可以使用Excel或函数,如下所示
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
最后但并非最不重要的是用于数组的每个…下一个语句
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代码区分大小写。只需补充一点:像If A=B或C这样的语句最好被视为A=B或C,其中B或C是按位或表达式B和C。当然,要执行此按位或表达式,必须有两个数字,因此,执行String1或String2时会出现类型不匹配错误,这是一个无效的操作。为什么VB对位运算符和逻辑运算符使用相同的关键字,这是我无法理解的,我一直想在SO文档中介绍的一些内容……为了完整起见,如果Field2类似于*[A-D]-[1-2]或Field2类似于*D-3,那么也可以使用。