问题
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 theApplication.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