关闭文件对话框时出现400错误消息

时间:2015-05-07 18:46:51

标签: excel vba excel-vba

我使用以下代码获取文件位置。我在一个单独的代码中使用GetFile的文件位置,该代码将CSV数据导入到我的一个工作表中。

我遇到的问题是文件对话框打开时,如果我没有选择文件并单击取消,我会收到400错误消息。有人可以让我知道如何摆脱这个错误信息吗?

Function GetFile() As String
Dim filename__path As Variant

filename__path = Application.GetOpenFilename(FileFilter:="Csv (*.CSV), *.CSV", Title:="Select File To Be Opened")
If filename__path = False Then Exit Function
GetFile = filename__path
End Function

正如下面的评论中所建议的那样,问题似乎并不在于函数,而在于宏调用函数并在函数错误时收到错误。宏代码发布在下面;我尝试使用GetFile = False的变体来结束with语句,但不断出现错误。

Sub Import_log()

ActiveWorkbook.Sheets("Bus List Import").Activate

With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & GetFile, Destination:=.Range( _
"$A$1"))
.Name = "logexportdata"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With

ActiveWorkbook.Sheets("Master").Activate

End Sub

目前我正在使用代码' On Error GoTo MasterTab:'在上面使用MasterTab:行上方的标签将活动工作表更改为Master选项卡。我知道这不是最好的做法,所以如果有人有答案,我会爱上:) 以下是完整的代码:

Sub Import_log()

ActiveWorkbook.Sheets("Bus List Import").Activate
On Error GoTo MasterTab:
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & GetFile, Destination:=Range( _
"$A$1"))
.Name = "logexportdata"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
MasterTab:
ActiveWorkbook.Sheets("Master").Activate

End Sub

1 个答案:

答案 0 :(得分:0)

如果没有选择文件,您可能想要停止宏。然后更换
    If filename__path = False Then Exit Function


   If filename__path = False Then End

退出函数不会停止你的宏,如果你从另一个函数调用GetFile,如果你试图用GetFile = vbNullString或其他意外值做某事就会引发错误

相关问题