将所有工作簿工作表复制到新工作簿VBA

时间:2016-01-29 21:06:31

标签: excel vba excel-vba

我正在使用此代码将工作簿中的每个工作表复制到一个新工作表并且工作正常但它会反转工作表的顺序,是否会阻止它执行此操作?

Sub copy()

'copies all the sheets of the open workbook to a new one
Dim thisWb As Workbook, wbTemp As Workbook
Dim ws As Worksheet

On Error GoTo Whoa

Application.DisplayAlerts = False

Set thisWb = ThisWorkbook
Set wbTemp = Workbooks.Add

On Error Resume Next
For Each ws In wbTemp.Worksheets
    ws.Delete
Next
On Error GoTo 0

For Each ws In thisWb.Sheets
    ws.copy After:=wbTemp.Sheets(1)
Next
wbTemp.Sheets(1).Delete

'save vba code here
Application.Dialogs(xlDialogSaveAs).Show Range("CA1").Text & "- (Submittal) " & Format(Date, "mm-dd-yy") & "_" & Format(Time, "hhmm") & ".xlsx"



LetsContinue:
Application.DisplayAlerts = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue

End Sub

我复制了所有工作表,这样我就可以将其保存为不同的文件扩展名,这是我找到的唯一方法。

工作簿复制之前 enter image description here

复制后的工作簿 enter image description here

2 个答案:

答案 0 :(得分:2)

根据斯科特·克兰纳(Scott Craner)的评论,OP表示其有效:

更改

ws.copy After:=wbTemp.Sheets(1)

收件人:

ws.copy After:=wbTemp.Sheets(wbTemp.Worksheets.Count)

答案 1 :(得分:0)

如果您只想更改文件格式

  

(我复制了所有的工作表,所以我可以将它保存为不同的文件扩展名,这是我找到的唯一方法。)

然后你可以试试这段代码:

Sub Test()
    fn = Range("CA1").Text & "- (Submittal) " & Format(Now, "mm-dd-yy_hhmm")
    fileSaveName = Application.GetSaveAsFilename(InitialFileName:=fn, fileFilter:="Excel Workbook (*.xlsx), *.xlsx")
    If fileSaveName <> False Then
     Application.DisplayAlerts = False
     ActiveWorkbook.SaveAs fileSaveName, xlOpenXMLWorkbook
     Application.DisplayAlerts = True
    End If
End Sub