EP04. “Type Mismatch 类型不匹配错误”
🔒 登录后可标记已读- Type Mismatch(类型不匹配)错误,发生在把不符合变量类型的值塞进变量的时候
- 这篇讲这个错误怎么发生、
InputBox为什么特别容易踩到这个坑 - 也讲怎么用
Variant+IsNumeric避开它 - 前置知识:基本的变量声明和数据类型概念
重点内容
适用版本
桌面版通用(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 检查使用者输入的到底是不是数字,是才往下计算,不是就提示重新输入,不会直接报错中断。
学完你会
- ✅ 看懂 Type Mismatch 错误是怎么发生的
- ✅ 知道
InputBox回传的一定是文字,直接塞进 Integer 变量容易出错 - ✅ 用
Variant+IsNumeric检查输入,避免宏直接当掉
常见错误
- 变量类型设得太死(比如 Integer),却拿来接 InputBox 这种一定会回传文字的来源
- 没有用 IsNumeric 先检查输入内容,使用者随便乱打就让整个宏当掉
- 把 Type Mismatch 和 EP01 的「变量未声明」错误搞混,两者报错时机和原因不一样
Sources
Blog / Website: