使用字符串变量作为Text连接

时间:2015-09-12 02:23:36

标签: excel excel-vba excel-2010 vba

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

我已经为脚本成功遍历所有文件奠定了基础,在名为FullConnection的字符串变量中设置每个文件的完整路径。

我知道变量正确设置了文件的完整路径,因为我在导入发生之前的消息框中显示它。

我的问题是

  

为什么以下代码不能用于传递变量作为连接名称?

我确定这是愚蠢的我做错了但似乎无法解决。硬编码单个文件路径工作正常,所以我知道它只是给我提出问题的连接变量。

我在这个主题上看过MSDN article,但是他们没有说明如何将变量设置为连接字符串,只是硬编码文本文件的实际路径。任何帮助表示赞赏!

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

1 个答案:

答案 0 :(得分:3)

您已将路径变量封装到带引号的字符串中。您需要将路径变量连接到该引用字符串的右端。

doc.SelectNodes("//Version[@Name='" + version + "']/Note")

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