2016-10-24 26 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