2017-04-20 129 views
0

錯誤處理我使用的是標準的Workbooks.OpenText功能但是當我擊中取消,其調試到我的代碼,我不想要的。相反,我想要一個錯誤處理程序,所以如果我點擊取消,會出現一個錯誤框,指出「沒有選擇文件」。我無法弄清楚如何認識到這個OpenText被取消了。有關WorkBooks.OpenText命令

Set myfile = Application.FileDialog(msoFileDialogFolderPicker) 
Workbooks.OpenText Filename:=myfile, DataType:=xlDelimited, 
Origin:=xlWindows, Other:=True, OtherChar:="," 
+0

我不明白「......當我擊中取消,其調試到我的代碼......」。當我使用「OpenText」時,文件打開並且沒有機會取消。 – xidgel

+0

oops;我添加了一個打開FileDialog的前一行。從本質上講,正在發生的事情是在標準的Excel文件對話框,當我打取消,它進入調試程序。我希望用戶看到錯誤消息,當他們擊中取消文件對話框的「打開文件」的Excel選項。 – illmatic

回答

0

你可以這樣做:

Sub MySub() 
    Dim fd As FileDialog 
    Dim vrtSelectedItem As Variant 

    Set fd = Application.FileDialog(msoFileDialogFilePicker) 

    With fd 
     ' TODO configure file dialog 
     ' .AllowMultiSelect = ??? 
     ' .Filters = ??? 
     ' ... 

     If .Show = -1 Then 
      ' TODO code to handle FileDialog OK button 
      ' Depending on settings user may be able to select multiple items 
      For Each vrtSelectedItem in .SelectedItems 
       Debug.Print vrtSelectedItem 
       ' Workbooks.OpenText Filename:=vrtSelectedItem, ... 
      Next vrtSelectedItem 
     Else 
      ' TODO code to handle FileDialog Cancel button 
      Debug.Print "user hit cancel" 
     End If 
    End With 

    Set fd = Nothing 
End Sub 

希望幫助