如何修改此代码以通过FileDialog导入文本文件?

您好,我正在尝试从一个基于FileDialog从设置path的文件夹中导入文本文件? 我有一个代码,导入一个文本文件,但它只打开了一个通用的C:\\path,我应该如何修改下面的代码,以打开指定path的文件夹?

 Sub ImportTextFile() Dim fName As String, LastRow As Long fName = Application.GetOpenFilename("Text Files (*.txt), *.txt") If fName = "False" Then Exit Sub LastRow = Range("A" & Rows.Count).End(xlUp).Row + 1 With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fName, _ Destination:=Range("A" & LastRow)) .Name = "sample" .FieldNames = True .RowNumbers = False .FillAdjacentFormulas = False .PreserveFormatting = True .RefreshOnFileOpen = False .RefreshStyle = xlInsertDeleteCells .SavePassword = False .SaveData = True .AdjustColumnWidth = True .RefreshPeriod = 0 .TextFilePromptOnRefresh = False .TextFilePlatform = 437 .TextFileStartRow = 1 .TextFileParseType = xlDelimited .TextFileTextQualifier = xlTextQualifierNone .TextFileConsecutiveDelimiter = True .TextFileTabDelimiter = False .TextFileSemicolonDelimiter = False .TextFileCommaDelimiter = True .TextFileSpaceDelimiter = False .TextFileOtherDelimiter = "" & Chr(10) & "" .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, _ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 End Sub 

任何帮助将不胜感激!

我做了以下更改到代码的开始,但现在我得到“1004应用程序定义的错误”

 Sub ImportTextFile() Dim fName As FileDialog, LastRow As Long Set fName = Application.FileDialog(msoFileDialogOpen) fName.InitialFileName = "\\olscmesf003\gcm_emea\TCU_REPORTS\APPS\Reports\Regional\Pointsec for PC Web RH\2017\" If fName = "False" Then Exit Sub 

在打开文件之前使用ChDir可能会有所帮助。 我会评论,但没有足够的声誉,所以发布在这里。

例如

 Sub ImportTextFile() ChDir "C:/yourpath/folder/etc" Dim fName As String, LastRow As Long ....