VBA:如何使用InputBox在将.txt文件导入Excel时提示用户input.txt文件path?

我一直在关注一个线程,在那里向我展示了如何在VBA编辑器中使用查询表将一个.txt文件从特定path导入到工作表中。

代码如下:

Sub Sample() With ActiveSheet.QueryTables.Add(Connection:= _ "TEXT;C:\Sample.txt", Destination:=Range("$A$1") _ ) .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 = xlTextQualifierDoubleQuote .TextFileConsecutiveDelimiter = False .TextFileTabDelimiter = True .TextFileSemicolonDelimiter = False .TextFileCommaDelimiter = True .TextFileSpaceDelimiter = False .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1) .TextFileTrailingMinusNumbers = True .Refresh BackgroundQuery:=False End With End Sub 

我试图修改代码,以便不必每次硬编码path,而是提示用户使用InputBox将path作为string存储在variables中,然后调用该variables而不是path。

我不断收到关于.Refresh BackgroundQuery:= False行的错误。

下面是我修改后的代码。

 Option Explicit Sub importEXP() Dim txtloc As String txtloc = InputBox("Provide path of .txt file to analyze") With ActiveSheet.QueryTables.Add(Connection:="TEXT;textloc", destination:=Range("$A$1")) .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 = xlTextQualifierDoubleQuote .TextFileConsecutiveDelimiter = False .TextFileTabDelimiter = True .TextFileSemicolonDelimiter = False .TextFileCommaDelimiter = True .TextFileSpaceDelimiter = False .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1) .TextFileTrailingMinusNumbers = True .Refresh BackgroundQuery:=False End With End Sub 

任何帮助表示赞赏,

谢谢

您需要更换该行:

 With ActiveSheet.QueryTables.Add(Connection:="TEXT;textloc", destination:=Range("$A$1")) 

附:

 With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & textloc, destination:=Range("$A$1")) 

VBA中的双引号不会扩展variables(就像在PowerShell和Perl中可以做的那样); 你必须明确地连接。

更改
Connection:="TEXT;textloc"

Connection:="TEXT;" & textloc

你需要改变

 With ActiveSheet.QueryTables.Add(Connection:="TEXT;textloc", destination:=Range("$A$1")) 

 With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & textloc, destination:=Range("$A$1")) 

textloc是一个variables,所以它不能放在引号内。