如何解决VBA Do循环中按取消按钮出现的类型13错误并终止宏
修复VBA MsgBox图标演示宏的取消按钮问题
我来帮你解决这个问题——你的代码触发错误13的原因很明确:当用户点击InputBox的取消按钮时,InputBox返回的是空字符串,而你把它直接赋值给了Integer类型的arg变量,这就导致了类型不匹配错误。另外,当前代码也没处理MsgBox取消按钮的终止逻辑,我给你修改后的代码并解释关键改动:
Sub msgbox_icons() Dim t As String, arg As Variant Dim inputNum As Long t = "Message Box Icons Demo" Do arg = InputBox(prompt:="Enter below one of the integers: (16, 32, 48 or 64):", Title:=t) ' 处理InputBox取消操作:返回空值时直接终止宏 If arg = "" Then Exit Sub End If ' 验证输入是否为有效数字,避免非数字输入导致的错误 If Not IsNumeric(arg) Then MsgBox "Please enter a valid integer!", vbExclamation + vbOK, t Continue Do ' 回到循环开头重新输入 End If inputNum = CLng(arg) ' 用Select Case替代ElseIf,让逻辑更清晰 Select Case inputNum Case 16 If MsgBox(inputNum & "<=> Critical Message Icon", vbCritical + vbOKCancel, t) = vbCancel Then Exit Sub Case 32 If MsgBox(inputNum & "<=> Warning Query Icon", vbQuestion + vbOKCancel, t) = vbCancel Then Exit Sub Case 48 If MsgBox(inputNum & "<=> Warning Message Icon", vbExclamation + vbOKCancel, t) = vbCancel Then Exit Sub Case 64 If MsgBox(inputNum & "<=> Information Message Icon", vbInformation + vbOKCancel, t) = vbCancel Then Exit Sub Case Else If MsgBox(inputNum & "<=> non-existent icon type", vbOKCancel, t) = vbCancel Then Exit Sub End Select Loop End Sub
关键改动说明:
- 改用Variant类型存储InputBox返回值:InputBox返回的是字符串(用户输入内容)或空值(点击取消),Variant类型可以兼容这两种情况,彻底避免类型不匹配错误
- InputBox取消处理:当检测到
arg为空时,直接执行Exit Sub终止整个宏 - 增加输入有效性验证:用
IsNumeric()检查输入是否为数字,如果不是就提示用户并重新进入输入环节 - MsgBox取消处理:每个MsgBox调用后判断返回值,若用户点击取消则立即终止宏
- 用Select Case优化逻辑:相比多个ElseIf,Select Case让条件判断更清晰易维护
内容的提问来源于stack exchange,提问作者Anmol Seth
相关产品推荐
相关产品推荐

