Sunday, February 3, 2019

excel - VBA returns error 1004 while trying to copy worksheet to another workbook




I have question: while trying to copy a worksheet to another workbook I get an error (error 1004 ).

This is my code:



Sub CopyWorksheet()
Application.ScreenUpdating = False
Dim BonusRatesWB As Workbook
Dim appExcel As Application

Set appExcel = New Application
appExcel.Visible = False
Set BonusRatesWB = appExcel.Workbooks.Open("D:\Documents\Overdraft\OVERDUE customers\HARD COLLECTION\Hard Collectors Bonus Calc\BonusRates\ProblemLoansOfficerBonusRates15Sep2017.xlsx")

With ThisWorkbook
BonusRatesWB.Sheets(1).Copy After:=.Sheets(.Sheets.Count)
End With
BonusRatesWB.Close

appExcel.Quit
Application.ScreenUpdating = True


End Sub




I assume there's something missing/wrong with my object variables, but I was unable to figure it out. Help would be highly appreciated.
Many thanks in advance.


Answer



Expanding on the answer/revision , it seems unnecessary to open a new instance of Excel.Application just to open/copy a worksheet (actually this is the source of your 1004 error, see below).



Open it in the same instance, incorporating the other answer as well:



Sub CopyWorksheet()    
Application.ScreenUpdating = False

Dim BonusRatesWB As Workbook
Set BonusRatesWB = appExcel.Workbooks.Open("D:\Documents\Overdraft\OVERDUE customers\HARD COLLECTION\Hard Collectors Bonus Calc\BonusRates\ProblemLoansOfficerBonusRates15Sep2017.xlsx")
With ThisWorkbook
BonusRatesWB.Sheets(1).Copy After:=.Sheets(.Sheets.Count)
BonusRatesWB.Close
End With
Application.ScreenUpdating = True
End Sub



I don't think you Copy worksheet like this across two different Excel Applications, and that seems to be the source of the 1004 error.




I don't get why wouldn't it work with a new instance




This is by design limitation:




NOTE: You cannot move or copy worksheets between workbooks that are open in separate instances of Excel. If a workbook is opened in a separate instance of Excel — for example, this can happen when you open that workbook from a Windows SharePoint Services site — make sure that you open that workbook in the same instance of Excel instead by browsing to it in the Open dialog box (File tab, Open).





If you must open in a new instance, then you can use a workaround as suggested in this answer, by simply saving the sheet to a new/temporary file, and then opening that from the origin instance of Excel, in order to copy/paste. It's more overhead, but if you need to do it that's the only way.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...