如果出现错误,我一直在搞清楚如何弹出msg框。我有下面的代码,但如果有错误并且退出sub。
,此代码不会跳转到错误处理程序Sub Validate_Region()
Dim str_DEPARTMENT_NAME As String
On Error GoTo Reion_Error
If Left(Range("M4"), 2) = "As" Then
str_DEPARTMENT_NAME = "India"
ElseIf Left(Range("M4"), 2) = "ME" Then
str_DEPARTMENT_NAME = "Middle East"
End If
'Get value of region selected in Master File
str_regionvalue = Workbooks("Master Report").Sheets("Home").Range("T8")
If str_regionvalue = str_DEPARTMENT_NAME Then
MsgBox ("You have selected " & str_regionvalue & " region"), vbInformation
End If
Exit Sub
Reion_Error:
MsgBox ("Please select the correct Region.") & vbNewLine & vbNewLine & ("You have selected " & str_regionvalue & " region" & " In Home Sheet of Master Report and pulled the data for " & str_DEPARTMENT_NAME & " region"), vbCritical
ActiveWorkbook.Close
End Sub
答案 0 :(得分:0)
检查语法,msgbox语句中有不少不必要的括号和逗号。尝试类似:
returnval = MsgBox ("Put message here" , vbInformation)
OR
MsgBox "another message " & vbnewline & "some more message", vbcritical
代码看起来很好并且现在可以编译,但我认为您的错误可能在其他地方。可能在:
str_regionvalue = Workbooks("Master report").Sheets("Home").Range("T8")
我建议:
在代码顶部添加'Option Explicit' - 它将强制您声明所有变量(未声明str_regionvalue)
设置您的工具>> VB编辑器中的选项:“打破未处理的错误”。
答案 1 :(得分:0)
我只是复制/粘贴你的代码,它对我很有用:
我不知道这个子被调用的地方以及str_regionvalue
上使用的变量类型(看起来像Variant)
那你怎么能这样做:
Exit Sub
。 Reion_Error:
If Err.Number <> 0 Then
MsgBox ("Please select the correct Region.") & vbNewLine & vbNewLine & ("You have selected " & str_regionvalue & " region" & " In Home Sheet of Master Report and pulled the data for " & str_DEPARTMENT_NAME & " region"), vbCritical
'by the way, you can try to set ActiveWorkbook.Saved to True, to get rid from pop-ups on Close
ActiveWorkbook.Close
End If
debug.print err.number
查找错误编号或放置一些stop
来手动执行此操作)。或者将err.number
添加到手表并检查Break when value changes
,以便您可以跟踪引发和清除错误的位置(如果引发)。P.S。你有一些荒谬的MsgBoxes,如果你真的喜欢括号,请使用它们:
Call MsgBox("Please select the correct Region." & vbNewLine & vbNewLine & _
"You have selected " & str_regionvalue & " region" & " In Home Sheet of Master Report and pulled the data for " & str_DEPARTMENT_NAME & " region", vbCritical)
答案 2 :(得分:0)