Good afternoon, I have some simple code that would copy a range from some workbooks and paste as values in another workbook - that works fine.
The first workbook is linked by formulae to a known output file.
I've just been told that the second workbook would only contain worksheets that contain data as it is uploaded to a Government portal. I thought that I would put in a check to compare the names and only copy if they matched. Now, even before I've figured out how to execute a loop to find the corresponding worksheet in the second workbook it fails to execute - Sheets 4 are both aggregate sheets so they exist in both.
When I get to the (xlPasteValues) line it errors:-
What has gone wrong and can you help with the syntax for a loop to look for the correct workbook - which will always be in wb1?
Many thanks,
D€$
Code:
Private Sub CopyDataButton_Click_Old()
Dim x As Integer
Dim wb1 As String 'First Workbook
Dim wb2 As String 'Second Workbook
Dim LastSheet As Integer
wb1 = "MARPROV.xls"
wb2 = "MARPROV_2.xlsx"
LastSheet = Workbooks(wb1).Sheets.Count - 5
For x = 3 To LastSheet
Application.ScreenUpdating = False
Workbooks(wb1).Sheets(x).Range("J11:W11").Copy
Workbooks(wb2).Sheets(x).Range("J11").PasteSpecial (xlPasteValues)
Next x
Application.ScreenUpdating = True
MsgBox ("All Data Copied")
End Sub
The first workbook is linked by formulae to a known output file.
I've just been told that the second workbook would only contain worksheets that contain data as it is uploaded to a Government portal. I thought that I would put in a check to compare the names and only copy if they matched. Now, even before I've figured out how to execute a loop to find the corresponding worksheet in the second workbook it fails to execute - Sheets 4 are both aggregate sheets so they exist in both.
Code:
LastSheet = Workbooks(wb1).Sheets.Count
LastSheetTwo = Workbooks(wb2).Sheets.Count
For y = 4 To LastSheetTwo
For x = 4 To LastSheet
''Application.ScreenUpdating = False
MsgBox (Workbooks(wb1).Sheets(x).Name) 'This is temporary - just to check the names
MsgBox (Workbooks(wb2).Sheets(y).Name) 'This is temporary - just to check the names
If Workbooks(wb1).Sheets(x).Name = Workbooks(wb2).Sheets(y).Name Then
Workbooks(wb1).Sheets(x).Range("J11:W11").Copy
Workbooks(wb2).Sheets(y).Range("J11").PasteSpecial (xlPasteValues)
End If
Next x
Next y
When I get to the (xlPasteValues) line it errors:-
Run-time error '1004':
Application-defined or object-defined error
What has gone wrong and can you help with the syntax for a loop to look for the correct workbook - which will always be in wb1?
Many thanks,
D€$