Copy a worksheet to a new workbook with paste values and keeping formats

情到浓时终转凉″ 提交于 2020-08-10 19:43:28

问题


I am trying to copy one worksheet to a new workbook, pasting all formulas as values while remaining all formats, sheetname, etcetera. The new file name should be "University" and stored on the same location as the original file. I have been struggling with this, as it keeps returning an

"Error 1004: PasteSpecial method of Range class failed"

with my current (copied) script:

Sub new_workbook()

Dim Output As Workbook
Dim FileName As String

Set Output = Workbooks.Add
Application.DisplayAlerts = False

ThisWorkbook.Worksheets("Report").Copy

Selection.PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=True, Transpose:=False

FileName = ThisWorkbook.Path & "\" & "University.xlsx"
Output.SaveAs FileName

End Sub

回答1:


Worksheet.Copy with no Before or After specified creates a new workbook, so just work off of that.

More detail from the docs:

If you don't specify either Before or After, Microsoft Excel creates a new workbook that contains the copied Worksheet object. The newly created workbook holds the Application.ActiveWorkbook property and contains a single worksheet.

Sub new_workbook()

    ThisWorkbook.Worksheets("Report").Copy '<-- creates a new workbook with a copy of your sheet

    Dim Output as Workbook
    Set Output = ActiveWorkbook

    With Output.Worksheets(1).UsedRange
        .Value = .Value '<-- changes all formulas to values
    End With

    Dim FileName As String
    FileName = ThisWorkbook.Path & "\University.xlsx"

    Application.DisplayAlerts = False
    Output.SaveAs FileName

End Sub


来源:https://stackoverflow.com/questions/62326725/copy-a-worksheet-to-a-new-workbook-with-paste-values-and-keeping-formats

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