[英]how to avoid runtime error while displaying a message box in excel vba
我试图显示一个消息框,如果未选择文件,则显示“未选择文件”。我的问题是正在显示消息框,但是当我单击“确定”时,我收到运行时错误1004,提示“未找到文件或检查文件”文件的拼写和位置”。有人可以帮助我如何避免此错误。谢谢
Dim Wbk1 As Workbook, Wbk2 As Workbook, Wbk3 As Workbook
Dim Sh1 As Worksheet, Sh2 As Worksheet, Sh3 As Worksheet
Dim tmp1 As String, tmp2 As String, tmp3 As String
Dim TextBox1 As String
Dim TextBox2 As String
Dim TextBox3 As String
tmp1 = Sheets("Sheet1").TextBox1.Value
If Len(Trim(tmp1)) = 0 Then
MsgBox "file not chosen"
End If
Exit sub
tmp2 = Sheets("Sheet1").TextBox2.Value
If Len(Trim(tmp2)) = 0 Then
MsgBox "destination file not selected"
End If
Exit sub
tmp3 = Sheets("Sheet1").TextBox3.Value
If Len(Trim(tmp3)) = 0 Then
MsgBox "mapping file not selected"
End If
Exit sub
Set Wbk1 = Workbooks.Open(tmp1)
Set Wbk2 = Workbooks.Open(tmp2)
Set Wbk3 = Workbooks.Open(tmp3)
Set Sh1 = Wbk1.Sheets("Inventory")
Set Sh2 = Wbk2.Sheets("Inventory")
Set Sh3 = Wbk3.Sheets("Sheet1")
您提供的代码片断对我来说效果很好,所以我将假定您在此例程中有其他代码,这些其他代码在您单击msgbox中的“确定”后仍将继续运行。 该代码最有可能试图访问文件名=什么都不会导致您收到错误消息。 基于此假设,为什么不添加:
exit sub
正在查看您的msgbox代码。
如John所述,您必须使用Exit For
。 但是您在错误的地方使用它们。
将control
声明为变量也是一个坏主意。 是的,我指的是
Dim TextBox1 As String
Dim TextBox2 As String
Dim TextBox3 As String
尝试这个
Sub Sample()
Dim Wbk1 As Workbook, Wbk2 As Workbook, Wbk3 As Workbook
Dim Sh1 As Worksheet, Sh2 As Worksheet, Sh3 As Worksheet
Dim tmp1 As String, tmp2 As String, tmp3 As String
tmp1 = ThisWorkbook.Sheets("Sheet1").TextBox1.Value
If Len(Trim(tmp1)) = 0 Then
MsgBox "file not chosen"
Exit Sub
End If
tmp2 = ThisWorkbook.Sheets("Sheet1").TextBox2.Value
If Len(Trim(tmp2)) = 0 Then
MsgBox "destination file not selected"
Exit Sub
End If
tmp3 = ThisWorkbook.Sheets("Sheet1").TextBox3.Value
If Len(Trim(tmp3)) = 0 Then
MsgBox "mapping file not selected"
Exit Sub
End If
Set Wbk1 = Workbooks.Open(tmp1)
Set Wbk2 = Workbooks.Open(tmp2)
Set Wbk3 = Workbooks.Open(tmp3)
Set Sh1 = Wbk1.Sheets("Inventory")
Set Sh2 = Wbk2.Sheets("Inventory")
Set Sh3 = Wbk3.Sheets("Sheet1")
End Sub
完成所有这些操作后,如果仍然收到消息"file not found or check the spelling and location of the file"
则表明文本框中提到的路径不正确。 您实际上可以使用DIR
来检查路径是否正确。
例如
If Dir(tmp1) = "" Then
Msgbox "Incorrect Path/File. Please ensure that the Textbox Has correct path"
Else
Set Wbk1 = Workbooks.Open(tmp1)
End If
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.