Microsoft Lab
全部软件
Excel变量(Variables)约 4 分钟

Type Mismatch 类型不匹配错误

重点内容


适用版本

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


最基础的类型不匹配

Dim number As Integer
number = "bike"

number 被声明成 Integer(整数),却被赋值成文字 "bike",直接触发 Type Mismatch 错误。

📷 画面提示

运行代码后弹出的 "Run-time error '13': Type mismatch" 报错对话框


InputBox 容易触发的坑

Dim number As Integer
number = InputBox("Enter a number", "Square Root")
MsgBox "The square root of " & number & " is " & Sqr(number)

InputBox 传回来的永远是文字(字符串),如果使用者随便打了非数字的内容,或者字符串本身没办法转成 Integer,同样会报 Type Mismatch。


解法:改用 Variant + IsNumeric 判断

Dim number As Variant
number = InputBox("Enter a number", "Square Root")
If IsNumeric(number) Then
    MsgBox "The square root of " & number & " is " & Sqr(number)
Else
    MsgBox "Please enter a number"
End If

把变量类型改成 Variant(弹性类型,什么都能装),再用 IsNumeric 检查使用者输入的到底是不是数字,是才往下计算,不是就提示重新输入,不会直接报错中断。


学完你会

常见错误

  • 变量类型设得太死(比如 Integer),却拿来接 InputBox 这种一定会回传文字的来源
  • 没有用 IsNumeric 先检查输入内容,使用者随便乱打就让整个宏当掉
  • 把 Type Mismatch 和 EP01 的「变量未声明」错误搞混,两者报错时机和原因不一样

Sources

Blog / Website:

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