sparkytech
Board Regular
- Joined
- Mar 6, 2018
- Messages
- 96
- Office Version
- 365
- 2019
I have the code below, and get a Run-time error '1004' "PasteSpecial method of Range class failed" at:
The original sheet has an "Export" button which runs this macro, and exports to another workbook. I didn't write this code, but modified both workbooks structure. Workbook 1 row 5 and down used to export to "Export" workbook, starting at row 1 and down. Now it exports the same table starting at row 5, but is supposed to paste at row 5 on the export workbook. Any ideas why this error?
VBA Code:
DestWkb.Sheets(1).Cells(1, 1).PasteSpecial
The original sheet has an "Export" button which runs this macro, and exports to another workbook. I didn't write this code, but modified both workbooks structure. Workbook 1 row 5 and down used to export to "Export" workbook, starting at row 1 and down. Now it exports the same table starting at row 5, but is supposed to paste at row 5 on the export workbook. Any ideas why this error?
VBA Code:
Sub ExportCleanExcel(control As IRibbonControl)
'Exports the information in the master sheet to a chosen excel file; will just move
'the data without macros or other extra features
Dim FileToOpen As Variant
Dim DestWkb As Workbook
Dim MasBotRow As Long
Dim MasLasCol As Long
'Turn off screen updates to improve performance
Application.ScreenUpdating = False
'Allows user to select a file to export to using the traditional open file window
FileToOpen = Application.GetOpenFilename("All Excel Files (*.xls?), *.xls?", , "Please export file")
'If the user selects cancel when chosing a file to open FileToOpen is set to FALSE
'Using this we can check if a file was actually selected before continuing
If FileToOpen <> False Then
'Find the bottom row and last column of the table on the master sheet
MasBotRow = Sheet1.Cells.Find(What:="*", After:=Range("A1"), LookAt:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False).Row
MasLasCol = Sheet1.Cells.Find(What:="*", After:=Range("A1"), LookAt:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False).Column
'Copies the entire table from the master sheet
Sheet1.Range(Cells(1, 1), Cells(MasBotRow, MasLasCol)).Copy
'Open the file that was selected and then set that workbook as DestWkb
Set DestWkb = Application.Workbooks.Open(FileToOpen)
'Pastes the table into the destination file in the A1 cell of the first sheet
DestWkb.Sheets(1).Cells(1, 1).PasteSpecial
'Turn off alerts to avoid clipboard notices when closing the file
Application.DisplayAlerts = False
'Close the data file
DestWkb.Close True
'Turn back on alerts after closing the file
Application.DisplayAlerts = True
End If
Application.CutCopyMode = False
Range("A4").Select ' btn set cursor location to cell A4
'Turn back on screen updates
Application.ScreenUpdating = True
End Sub