使用stringvariables作为文本连接

我试图编写一个脚本,循环遍历所有文本文件在一个单一的目录,并将其导入Excel工作表。 它们都是相同的格式和文件types(.txt)。

我已经为脚本成功地循环遍历所有文件奠定了基础,将每个文件的完整path设置为名为FullConnection的stringvariables。

我知道这个variables是正确的设置文件的完整path,因为我在导入应该发生之前的消息框中显示它。

我的问题是这样的

为什么下面的代码不能作为连接名称传递variables?

我敢肯定这是愚蠢的,我做错了,但似乎无法解决。 对单个文件path进行硬编码可以正常工作,所以我知道这只是连接variables给我的问题。

我已经看到关于这个主题的MSDN文章 ,但是他们没有展示如何设置一个variables作为连接string,只是硬编码文本文件的实际path。 任何帮助表示赞赏!

 MsgBox fullConnection 'Start importing current file into Excel: With ActiveSheet.QueryTables.Add(Connection:="TEXT;<fullConnection>", Destination:=Range("$A$1") _ ) .Name = fullConnection .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 = 4 .TextFileParseType = xlDelimited .TextFileTextQualifier = xlTextQualifierDoubleQuote .TextFileConsecutiveDelimiter = False .TextFileTabDelimiter = True .TextFileSemicolonDelimiter = False .TextFileCommaDelimiter = False .TextFileSpaceDelimiter = False .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1) .TextFileTrailingMinusNumbers = True '.Refresh BackgroundQuery:=False End With 

您已将pathvariables封装在引用的string中。 您需要将pathvariables连接到引用string的右端。

 ActiveWorkbook.Worksheets.Add With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fullConnection, Destination:=Range("$A$1") _ ) ... 

我还添加了一个WorkSheets.Add方法 ,可以保证每个文本文件都被带入到一个新的工作表中。