excel - 在If语句中使用IsError

标签 excel vba error-handling

我有以下If -Statement:

If wb.Range("A1").Value = "n/a" Or wb.Range("A1").Value = "na" Then
    wb.Range("A2").Value = "-"
Else
    ...
End

直到A1包含#NV(错误,它不是字符串)并且代码给我错误13(类型不匹配),此方法才能正常工作。我试图简单地做到这一点:
If IsError(wb.Range("A1").Value) = True Or wb.Range("A1").Value = "n/a" Or wb.Range("A1").Value = "na" Then
    wb.Range("A2").Value = "-"
Else
    ...
End

但是,再次键入不匹配。

如果我像这样将其分开,它将起作用:
If IsError(wb.Range("A1").Value) = True Then
    wb.Range("A2").Value = "-"
ElseIf wb.Range("A1").Value = "n/a" Or wb.Range("A1").Value = "na" Then
    wb.Range("A2").Value = "-"
Else
     ...
End

这给我带来了两个问题:
  • 是否可以像在第二个代码段中尝试的那样以某种方式处理错误,而没有elseif而只有一个If-语句?
  • 为什么If IsError(wb.Range("A1").Value) = True Or wb.Range("A1").Value = "n/a"不起作用? VBA是否同时查看所有Or条件,并且其中之一返回错误,所以整个If语句是否相同?
  • 最佳答案

    VBA不支持

    Short Circuiting



    这就是IsError(wb.Range("A1").Value) = True Or wb.Range("A1").Value = "n/a" Or wb.Range("A1").Value = "na"不起作用的原因,因为它将检查所有条件。

    最好将wb.Range("A1").Value = "n/a" Or wb.Range("A1").Value = "na"放在elseif中。

    请参阅this

    关于excel - 在If语句中使用IsError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60373739/

    相关文章:

    java - Apache POI - 迭代 excel 中的列(XSSF)

    excel - 查找特定列中最后使用的单元格以及范围周围的边框

    vba - 排序,然后重新排序

    optimization - vbscript 中的 Err.clear

    validation - 验证错误中的位置信息

    r - 在 Excel 或 R 中将子子数据与父数据合并?

    excel - Google 电子表格 - 以持续时间格式转换总小时数

    error-handling - linux内核中的系统调用错误处理

    python - xlwings 与 openpyxl 阅读 Excel 工作簿的区别

    excel - Visual Basic for Applications(VBA)编译错误: Procedure declaration does not match description of event or procedure having the same name