Error in Copying a Sheet from One Workbook to an Another

佐手、 提交于 2020-01-06 03:44:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!