问题
Encountered below error in my vba code.
Run-time error '1004': Copy Method of Worksheet Class failed
Public Sub ExportAsCSV(savePath)
Set ws = Workbooks("OND Estimator").Worksheets("port") 'Sheet to export as CSV
Set wb = Application.Workbooks.Add
ws.Copy Before:=wb.Worksheets(wb.Worksheets.Count)
Application.DisplayAlerts = False 'Possibly overwrite without asking
wb.SaveAs Filename:=savePath, FileFormat:=xlCSV
Application.DisplayAlerts = True
wb.Close savechanges:=False
End Sub
回答1:
Just copy the worksheet to no location. This creates a new active workbook with a single worksheet (a copy of the original) ready to be saved as xlCSV.
Public Sub ExportAsCSV(savePath)
Workbooks("OND Estimator").Worksheets("port").Copy 'Sheet to export as CSV
Application.DisplayAlerts = False 'Possibly overwrite without asking
with activeworkbook
.SaveAs Filename:=savePath, FileFormat:=xlCSV
.Close savechanges:=False
end with
Application.DisplayAlerts = True
End Sub
回答2:
try
Public Sub ExportAsCSV(savePath)
Application.DisplayAlerts = False 'Possibly overwrite without asking
With Workbooks("OND Estimator").Worksheets("port").Parent
.SaveAs Filename:=savePath, FileFormat:=xlCSV
.Close savechanges:=False
End With
Application.DisplayAlerts = True
End Sub
回答3:
I found out the issue on this! I didn't realize hiding the sheets will cause the copy method to not work correctly...
Worksheets("port").Visible = xlVeryHidden
...so what I did is that I revealed the sheet before copying and then hid again once the copy is done.
Worksheets("port").Visible = True
Thank you guys for your helping me!
来源:https://stackoverflow.com/questions/52088589/error-in-copying-a-sheet-from-one-workbook-to-an-another