Microsoft Lab
全部软件
Excel宏错误(Macro Errors)约 4 分钟

Err Object Err 对象

重点内容


适用版本

桌面版通用(Excel 365 / 2021 / 2019 等)。


用 Err.Number / Err.Description 显示详细信息

Dim rng As Range, cell As Range
Set rng = Selection

For Each cell In rng
    On Error GoTo InvalidValue:
    cell.Value = Sqr(cell.Value)
Next cell

Exit Sub

InvalidValue:

MsgBox Err.Number & " " & Err.Description & " at cell " & cell.Address

Resume Next

出错时会显示错误代号、错误说明文字、以及是哪个单元格出错,比单纯写死一句提示更精确。


用 Select Case 针对不同错误代号给不同提示

InvalidValue:

Select Case Err.Number
    Case Is = 5
        MsgBox "Can't calculate square root of negative number at cell " & cell.Address
    Case Is = 13
        MsgBox "Can't calculate square root of text at cell " & cell.Address
End Select

Resume Next

错误代号 5(Invalid procedure call)代表负数开根号,13(Type mismatch)代表文字开根号,针对不同情况给出更友善的提示文字。


学完你会

常见错误

  • 只用一句固定的错误提示,不管什么错误都显示同一句话,使用者不知道具体问题出在哪
  • 用 Select Case 判断错误代号时,代号写错或漏了某个常见错误类型,导致提示信息不准确
  • 忘记 Err 对象的内容只在错误发生「当下」有效,之后的代码如果又执行了别的操作,Err 的内容可能已经被覆盖

Sources

Blog / Website:

  1. Err Object
只记在你的浏览器里,换设备不会同步。