excel - 使用字符串变量作为文本连接

标签 excel excel-2010 vba

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

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

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

我的问题是这样的:

why does the below code not work for passing in the variable as the connection name?

我确信我做错了一些愚蠢的事情,但似乎无法解决。对单个文件路径进行硬编码效果很好,所以我知道这只是连接变量给我带来了问题。

我已经看到了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

最佳答案

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

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

我还添加了 WorkSheets.Add method这应该保证每个文本文件都被带入一个新的工作表中。

关于excel - 使用字符串变量作为文本连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32534540/

相关文章:

python - 从python中的.eml文件解析excel附件

excel - 有没有一个excel公式可以将负数四舍五入?即轮(-2.5) = -2

vba - Excel 2010 VBA 在所有打开的文件中运行

excel - 如何检查单元格的当前值是否在所有先前单元格的某个值之内

ms-access - 如何关闭(卸载)表单

VBA循环通过文件夹公式粘贴问题

excel - Vba 查找完全匹配

excel - 在Excel中将多行滚动为一行

excel - VBA 2016中的错误处理程序

html - 在 VBA 电子邮件中设置指向 "word"的 Web 链接