I need to copy Data from Sheet1
of Workbook1
to Sheet2
of Workbook2
. I need to copy data of sheet 1 from A1
to AE
(LastRow) and paste the whole copied data to Q1
of Sheet2
of Workbook2
.
Here is my code:
Set wbkA = Workbooks.Open(Filename:="D:\Excel\Workbook1.xlsx")
For Each oSheet In wbkA.Sheets
If oSheet.Name = "Sheet1" Then
Set NewWorksheetA = wbkA.Worksheets(oSheet.Name)
End If
Next oSheet
Set wbkB = Workbooks.Open(Filename:="D:\Excel\Workbook2.xlsx")
For Each oSheet In wbkB.Sheets
If oSheet.Name = "Sheet2" Then
Set NewWorksheetB = wbkB.Worksheets(oSheet.Name)
End If
Next oSheet
''''''''''''''''''''''''''''''''''''''''''''''''''''''' for Loop for row and Column Starts here to compare the data
If Not NewWorksheetA Is Nothing Then
''''''''''''''''''''''''''''''''''''''''''''''''''''''' Getting Last Column index from current Worbook to Write the UpdateStatus
LastRow = NewWorksheetA.Cells(NewWorksheetA.Rows.Count, 2).End(xlUp).Row
'MsgBox "Last Row Number:" & LastRow
LastColumn = NewWorksheetA.Cells(8, NewWorksheetA.Columns.Count).End(xlToLeft).Column
'MsgBox "Last Column Number:" & LastColumn
Workbooks("D:\Excel\Workbook1.xlsx").Worksheets("Sheet1").Range("A1:AE" & LastRow).Copy _
Workbooks("D:\Excel\Workbook2.xlsx").Worksheets("Sheet2").Range("Q1")
End If
I am getting the below error
Run Time Error 9: Subscript out of range.
I would like to use the variable used for Workbook and sheet name
Replace this code:
Workbooks("D:\Excel\Workbook1.xlsx").Worksheets("Sheet1").Range("A1:AE" & LastRow).Copy _
Workbooks("D:\Excel\Workbook2.xlsx").Worksheets("Sheet2").Range("Q1")
with this:
NewWorksheetA.Range("A1:AE" & LastRow).Copy
NewWorksheetB.Range("Q1").PasteSpecial xlPasteAll
Application.CutCopyMode = False
Hope my answer helps. :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.