vba - 运行时错误 '13' : Type mismatch on IF combined with OR statement

标签 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

当我运行代码时,我收到以下消息: “运行时错误‘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

注意:我假设 i 是有效的行号

说明:

使用 If 语句进行比较时,不能说 If A = B or C。你应该单独比较。 如果 A = B 或 A = C 则。这里每个OR都是它自己的Boolean语句,即它将被单独评估。

当您进行多次此类比较时,最好使用 Select 语句,如上例所示。

关于vba - 运行时错误 '13' : Type mismatch on IF combined with OR statement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38727066/

相关文章:

php - 上传excel文件Laravel

python - Flask 和 Pandas ExcelWriter 不使用 BytesIO 更改列格式

excel - 在 Excel 中为多个查询共享数据库连接?

java - 如何使用jdbc连接将excel表中的数据存储到mysql数据库中

excel - 根据条件从范围中选择单元格值

vba - 在宏中使用工作表函数

vba - 数据透视表 : Detect When Pivot Field is Collapsed

vba - Let/Get 属性中的可选参数如何工作?

windows - 如何使用 Access/VBA 复制到剪贴板?

vba - 如果工作簿和工作表未处于事件状态,则无法使用范围