我试图将excel文件1的单元格(1,1)复制到excel文件2的单元格(1,1)。 但假设我已经在单元格(2,20)中放置了要打开的文件的名称,并且我想分配变量j = cells(2,20)并在复制文件的代码中使用它。我似乎遇到了问题。
这是我的代码:
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 :(得分: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
答案 1 :(得分: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