2015-02-24 59 views
1

我试图大量进口与数值名称的文本文件到一个单独的工作表中导入数据的文件名。 (包括.FileNames .RowNumbers时RefreshPeriod等命令。)使用变量或字符串作为使用查询表

循环创建工作表工作正常

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 

以及导入特定的单个文件,此行似乎也做工精细:

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

我想换成了“TEXT; C:\ TEMP \ load_excel \ 15.txt”更多的东西,让我用两个不同的变量来改变文件被导入:

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 
+0

可以粘贴确切的代码?这应该工作,但也有在例如循环中,代码甚至不编译一些错别字,而且很可能你不需要在启动和文件变量 – BrakNicku 2015-02-24 17:09:18

+0

结束关于双引号......不知道为什么DQ协议你会想要包括这些。 – 2015-02-24 17:23:46

+0

@ user3964075和@bp_精确的代码发布。我假定字符串文件需要**“**标记,以便它以纯文本为'被视为” TEXT; C:\ TEMP \ load_excel \ 15.txt“'是,当直接引用 – Theo 2015-02-24 19:13:31

回答

0

将这个您的循环中确切的代码。

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