Error in Copying a Sheet from One Workbook to an A

2019-07-29 22:41发布

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

3条回答
劳资没心,怎么记你
2楼-- · 2019-07-29 23:25

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楼-- · 2019-07-29 23:27

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
查看更多
Juvenile、少年°
4楼-- · 2019-07-29 23:35

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!

查看更多
登录 后发表回答