簡體   English   中英

如何在Excel VBA中顯示消息框時避免運行時錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM