2013-10-16 260 views
1

我找到了這段代碼,我試圖改變它,所以導入的數據存儲在另一個工作表中。Excel VBA超出範圍

第一個代碼是Destination:=ActiveCell,我試圖改變它,所以數據存儲在另一個工作表中。 我也試過這個:Destination:=Workbook.Sheets(CSV).Cells(1, 1))但它也不起作用。

我還在尋找代碼來自動選擇名稱爲export-price的最新csv文件,但是我還沒有找到解決方案。

Sub LoadProducts() 
    Dim fileName As String, folder As String 

    folder = "C:\Users\CP\Downloads\" 
    fileName = ActiveCell.Value 

    ActiveCell.Offset(1, 0).Range("A1").Select 


    With ActiveSheet.QueryTables _ 
     .Add(Connection:="TEXT;" & folder & fileName, Destination:=Workbook.Sheets(CSV).Cells(1, 1)) 
     .FieldNames = True 
     .RowNumbers = False 
     .FillAdjacentFormulas = False 
     .PreserveFormatting = True 
     .RefreshOnFileOpen = False 
     .RefreshStyle = xlInsertDeleteCells 
     .SavePassword = False 
     .SaveData = True 
     .AdjustColumnWidth = True 
     .RefreshPeriod = 0 
     .TextFilePromptOnRefresh = False 
     .TextFilePlatform = 850 
     .TextFileStartRow = 1 
     .TextFileParseType = xlDelimited 
     .TextFileTextQualifier = xlTextQualifierDoubleQuote 
     .TextFileConsecutiveDelimiter = False 
     .TextFileTabDelimiter = False 
     .TextFileSemicolonDelimiter = True 
     .TextFileCommaDelimiter = True 
     .TextFileSpaceDelimiter = False 
     .TextFileColumnDataTypes = Array(1, 1, 1, 1) 
     .TextFileTrailingMinusNumbers = True 
     .Refresh BackgroundQuery:=False 
    End With 
End Sub 

回答

2

您需要正確聲明您的對象然後使用它們。這是一個例子。按適用情況更改。

Dim wb As Workbook, thiswb As Workbook 
Dim ws As Worksheet, thisws As Worksheet 

'~~> Change as applicable 
Set thiswb = ThisWorkbook 
Set thisws = thiswb.Sheets("Sheet1") 

CSV = "Sheet1" 
Set wb = Workbooks.Open("C:\Blah Blah.xlsx") 
Set ws = wb.Sheets(CSV) 

With thisws.QueryTables _ 
    .Add(Connection:="TEXT;" & folder & Filename, Destination:=ws.Cells(1, 1)) 
+0

感謝您的支持。現在在文件夾中將會有更多的一個csv文件導入。當用戶下載一個新的窗口,給它一個新的號碼 出口price.csv 出口價格(2).csv格式 出口價格(3).csv格式 出口價格(4).csv格式 燦我使用代碼來選擇包含export-price的最新csv文件? – Tupolev

+0

是的,你可以這樣做,或者你可以使用文件對話框讓用戶選擇文件。 –

+0

你知道我是怎麼做的嗎 – Tupolev