我试图从对话框中处理错误或无文件选择。其余的代码工作得很好,但是当没有选择文件时,我收到来自VBA的以下错误消息:1004 False.xlsx找不到。您知道如何管理代码以防止弹出错误消息吗?
Sub OpeningExcelFile2()
Dim Finfo As String
Dim FilterIndex As Integer
Dim Title As String
Dim Filename As Variant
Dim wb As Workbook
Dim objWdApp As Object
Dim objWdDoc As Object
'Setup the list of file filters
Finfo = "Excel Files (*.xlsx),*xlsx," & _
"Macro-Enable Worksheet (*.xlsm),*xlsm," & _
"Word Files (*.docx),*.docx," & _
"All Files (*.*),*.*"
MultiSelect = True
'Display *.* by default
FilterIndex = 4
'Set the dialog box caption
Title = "Select a File to Open"
'Get the Filename
Filename = Application.GetOpenFilename(Finfo, _
FilterIndex, Title)
'Handle return info from dialog box
If Filename = False Then
MsgBox "No file was selected."
Else
MsgBox "You selected " & Filename
End If
If InStr(1, Filename, ".docx", vbTextCompare) > 0 Then
Set objWdApp = CreateObject("Word.Application")
objWdApp.Visible = True
Set objWdDoc = objWdApp.Documents.Open(Filename) '\\ Open Word Document
Else
Set wb = Workbooks.Open(Filename) '\\ Open Excel Spreadsheet
'how to bring application excel to the front like word in this code?
End If
End Sub
答案 0 :(得分:0)
如果未选择任何文件,请退出子例程:
If Filename = False Then
MsgBox "No file was selected."
Exit Sub
Else
MsgBox "You selected " & Filename
End If