问题
I'm using this VBA code that covers all my requisites to transform all my workbook, including pivot tables and formulas into values.
Option Explicit
Sub Copia()
Dim ws As Worksheet, pvt As PivotTable, aWs As Worksheet, lst As ListObject
Set aWs = ActiveWorkbook.ActiveSheet
For Each ws In ActiveWorkbook.Worksheets
With ws
For Each pvt In ws.PivotTables
With pvt.TableRange2
.Copy
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
Next pvt
For Each lst In .ListObjects
If Not lst.AutoFilter Is Nothing Then lst.Range.AutoFilter
Next
If .FilterMode Then .ShowAllData
If .AutoFilterMode Then .AutoFilter.ShowAllData
.UsedRange.Value = .UsedRange.Value
.Activate: .Cells(1, 1).Select
End With
Next
aWs.Activate
Application.CutCopyMode = False
End Sub
How can I adapt it to copy only my active sheet or a specific sheet into a new workbook?
Thanks!
MD
回答1:
you'd better generate a single worksheet handling sub to pass a worksheet to
like follows:
Option Explicit
Sub CopiaWS(ws As Worksheet)
Dim pvt As PivotTable, aWs As Worksheet, lst As ListObject
Set aWs = ActiveWorkbook.ActiveSheet
With ws
For Each pvt In ws.PivotTables
With pvt.TableRange2
.Copy
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End With
Next pvt
For Each lst In .ListObjects
If Not lst.AutoFilter Is Nothing Then lst.Range.AutoFilter
Next
If .FilterMode Then .ShowAllData
If .AutoFilterMode Then .AutoFilter.ShowAllData
.UsedRange.Value = .UsedRange.Value
.Activate: .Cells(1, 1).Select
End With
aWs.Activate
End Sub
this way you have separated code to handle e specific task thus:
uncluttering main code with variable unnecessary to the main task
making your code more maintainable and debuggable
in fact you now can have your main code concentrate on processing a single worksheet or a single one, without worrying of the process details you coded away in an already (hopefully) stable and robust Sub:
Sub Main()
' other "main" code
CopiaWS Worksheets("MySheetName") '<--| process a single worksheet
' other "main" code
End Sub
Sub MainAll()
Dim ws As Worksheet
' other "main" code
For Each ws In ActiveWorkbook.Worksheets
CopiaWS ws '<--| process current loop worksheet
Next ws
' other "main" code
End Sub
回答2:
Here are two ways to copy a worksheet from one workbook to another.
'Copy a worksheet "Sheet1" from workbook "Book1" to "Book2."
'Concise
Workbooks("Book1.xlsx").Sheets("Sheet1").Copy Before:=Workbooks("Book2").Sheets(1)
'As a standalone sub
Sub CopySheetFromBook1ToBook2(shtName As String, wb1Name As String, wb2Name As String)
Dim wb1 As Excel.Workbook
Dim wb2 As Excel.Workbook
' Open workbooks
Set wb1 = Workbooks.Open(wb1Name) ' or Set wb1 = ActiveWorkbook
Set wb2 = Workbooks.Open(wb2Name)
' Coy shtName from wb1 to wb2
wb1.Sheets(shtName).Copy Before:=wb2.Sheets(1)
End Sub
来源:https://stackoverflow.com/questions/39799241/copy-excel-sheet-to-another-excel-book-without-formulas