2016-10-24 53 views
0

我試圖將excel文件1的單元格(1,1)複製到excel文件2的單元格(1,1)中。 但是,假設我已將名稱我想在單元格(2,20)中打開的文件,我想分配變量j =單元格(2,20),並在複製文件的代碼中使用它。我似乎遇到了問題。將複製excel中的變量分配給excel文件

這裏是我的代碼:

Sub Copy_Workbook() 

j = Cells(2, 20) 

Workbooks.Open ("C:\Users\GNPOWER\Desktop\TRADERS\Jonel\practice\data fetching\" & j & ".xlsx") 

Workbooks("Practice_Copy_From.xlsm").Worksheets("Sheet1").Cells(1, 1) = _ 
Workbooks(" & j & "&.xlsx").Worksheets("Sheet1").Cells(1, 1).Value 

End Sub 

我失去了類似的聲明還是什麼?

運行程序時,我得到範圍9的下標。

+0

正如你應該把'選項Explicit'你的模塊即開始的最佳實踐。這將迫使你必須聲明所有的變量。這將有助於您長期考慮數據類型。 – nbayly

回答

0

您不必在工作簿名稱聲明中添加明確的引號。在我刪除的擴展名「& .xlsx」前面還有一個&符號。代碼如下:

Sub Copy_Workbook() 

Dim j As String, wb As Workbook 
j = Cells(2, 20).Value2 
Set wb = Workbooks.Open("C:\Users\GNPOWER\Desktop\TRADERS\Jonel\practice\data fetching\" & j & ".xlsx") 
ThisWorkbook.Worksheets("Sheet1").Cells(1, 1).Value2 = wb.Worksheets("Sheet1").Cells(1, 1).Value2 

End Sub 
0

你甚至都不需要打開「源」文件

Option Explicit 

Sub Copy_Workbook()   
    Dim pathName As String, fileName As String 

    fileName = Cells(2, 20).Value '<--| retrieve the file name from the currently active worksheet cell "A1" 
    pathName = "C:\Users\GNPOWER\Desktop\TRADERS\Jonel\practice\data fetching\" '<--| set the folder path where "source" workbooks resides 

    With Workbooks("Practice_Copy_From.xlsm").Worksheets("Sheet1").Cells(1, 1) '<--| reference your "target" cell 
     .Value = "='" & pathName & "[" & fileName & "]Sheet1'!$A$1" '<--| write a formula that references the proper cell in the proper worksheet of the proper workbook 
     .Value = .Value '<--| get rid of formula and leave value only 
    End With 
End Sub