2017-08-01 53 views
1

我一直在关注另一个线程,那里向我展示了如何在VBA编辑器中使用查询表来将.txt文件从特定路径导入到工作表中。VBA:如何使用InputBox在将.txt导入Excel时提示用户输入.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行。

下面是我修改后的代码。

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

您需要更换行:

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

附:

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

双引号不扩展变量(比如,你可以在PowerShell中和Perl一样);你必须明确地连接。

+0

谢谢aucuparia。这工作像一个魅力。你的解释是有道理的。 –

1

变化
Connection:="TEXT;textloc"

Connection:="TEXT;" & textloc

0

您需要更改

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

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

textloc是一个变量,所以必须不被放置在引号内。