使用variables或string作为文件名来使用查询表导入数据

我试图用数字名称导入大量的文本文件到一个单独的工作表。

创build工作表的循环工作正常

Dim i as integer 'initial file name Dim k as integer 'final file name i = Cells(3, 3).Value k = Cells(5, 3).Value Do while i <= k Worksheets.Add.Name = i i = i +5 Loop 

并且为了导入特定的单个文件,这一行也似乎正常工作(当包括.FileNames .RowNumbers。RefreshPeriod等命令时):

 With Activesheet.QueryTables.Add(Connection:="TEXT;C:\temp\load_excel\15.txt" _, Destination:=Range ("$A$1")) 

我想用更多的东西replace“TEXT; C:\ temp \ load_excel \ 15.txt”,允许我使用两个不同的variables来改变正在导入的文件:

 Dim Folder As String Dim File As String Dim DQ as String DQ = """" 'double quotation marks Folder = Cells(14, 2).Value 'cell which states C:\temp\load_excel\ File = DQ & "TEXT;" & Folder & i & ".txt" & DQ 'for i = 15 this gives "TEXT;C:\temp\load_excel\15.txt" 

有没有一种方法来合并这两个,所以我可以有这样的循环?

 Do while i <=k Worksheets.Add.Name = i Activesheet.QueryTables.Add(Connection:= File _, Destination:=Range ("$A$1")) i = i +5 Loop 

据我可以看到,这应该工作,但是当我尝试运行它时,我得到一个运行时错误“1004”:应用程序或对象定义的错误。 如果有人可以帮助,将不胜感激。

编辑:这里是确切的代码正在使用

 Sub ImportPLEtextFiles() Dim i As Integer ''initial file name Dim k As Integer ''final file name Dim DQ As String '' Double quotation marks Dim Folder As String Dim File As String i = Cells(3, 3).Value k = Cells(5, 3).Value DQ = """" Folder = Cells(14, 2).Value File = DQ & Folder & i & ".txt" & DQ Do While i <= k Worksheets.Add.Name = i File = DQ & "TEXT;" & Folder & i & ".txt" & DQ With ActiveSheet.QueryTables.Add(Connection:=File _ , Destination:=Range("$A$1")) .FieldNames = True .RowNumbers = False .FillAdjacentFormulas = False .PreserveFormatting = True .RefreshOnFileOpen = False .RefreshStyle = xlInsertDeleteCells .SavePassword = False .SaveData = True .AdjustColumnWidth = False .RefreshPeriod = 0 .TextFilePromptOnRefresh = False .TextFilePlatform = 850 .TextFileStartRow = 1 .TextFileParseType = xlDelimited .TextFileTextQualifier = xlTextQualifierDoubleQuote .TextFileConsecutiveDelimiter = False .TextFileTabDelimiter = True .TextFileSemicolonDelimiter = False .TextFileCommaDelimiter = False .TextFileSpaceDelimiter = False .TextFileColumnDataTypes = Array(1) .TextFileTrailingMinusNumbers = True .Refresh BackgroundQuery:=False End With i = i + 5 Loop End Sub 

把它放在你的循环中。

 File = "TEXT;" & Cells(14, 2).Value & i & ".txt" With Sheets(i).QueryTables.Add(Connection:= _ File, Destination:=Range("$A$1")) .Refresh BackgroundQuery:=False End With