2015-02-24 65 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