我一直关注其他线程,其中告诉我如何在VBA编辑器中使用查询表将.txt文件从特定路径导入工作表。
代码如下:
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
我试图修改代码,以便不必每次都对路径进行硬编码,而是提示用户输入带有InputBox的路径,该路径将路径存储为变量中的字符串,然后调用该变量而不是路径。
我不断收到有关.Refresh BackgroundQuery:= False line的错误。
以下是我修改后的代码。
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
感谢任何帮助,
谢谢
答案 0 :(得分:1)
更改
Connection:="TEXT;textloc"
到
Connection:="TEXT;" & textloc
答案 1 :(得分:0)
您需要更改
With ActiveSheet.QueryTables.Add(Connection:="TEXT;textloc", destination:=Range("$A$1"))
到
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & textloc, destination:=Range("$A$1"))
textloc
是一个变量,因此不能将其放在引号内。
答案 2 :(得分:0)
您需要替换以下行:
With ActiveSheet.QueryTables.Add(Connection:="TEXT;textloc", destination:=Range("$A$1"))
使用:
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & textloc, destination:=Range("$A$1"))
VBA中的双引号不会扩展变量(就像你在PowerShell和Perl中所做的那样);你必须明确地连接。