VBA将工作表从数组粘贴到新工作簿作为值

时间:2014-11-29 20:21:57

标签: vba excel-vba excel

我正在尝试编写这个小宏来复制存储在数组中的多个工作表,并将它们作为值粘贴到新工作簿中,并保留工作表'名称和顺序。我找到了一些解决方案,但并不完全符合我的情况。

Sub tryit()

Dim wo As Workbook, wn As Workbook
Dim so As Worksheet, sn As Worksheet
Dim MyArray As Variant

MyArray = Array("ar1", "ar2", "ar3")

Set wo = ActiveWorkbook
Set wn = Workbooks.Add

For Each so In wo.Worksheets(MyArray)
        Set sn = wn.Worksheets.Add
        sn.Name = so.Name
        so.Cells.Copy
        sn.[A1].PasteSpecial xlPasteValues
        sn.[A1].PasteSpecial xlPasteFormats
    Next so

wn.SaveAs Filename:=ThisWorkbook.Path & "\" & "Report"
wn.Close savechanges:=True

End Sub

结果问题:

  1. 我是将新工作表从数组添加到工作表1 2和3,如何替换它们而不是删除?
  2. 添加的工作表顺序相反(ark3,ark2,ark1)。
  3. 我已经看到了一些使用Lbound和Ubound函数的解决方案,但是我不确定如何将它们与循环结合起来,我想它会使代码更清晰?

    提前致谢。

1 个答案:

答案 0 :(得分:0)

我认为这可以解决您的问题。我不确定删除最后一张纸的最后部分。我不知道你想怎么处理:

Sub tryit()

Dim wo As Workbook, wn As Workbook
Dim so As Worksheet
Dim MyArray As Variant

MyArray = Array("ar1", "ar2", "ar3")

Set wo = ActiveWorkbook
Set wn = Workbooks.Add
'copy all worksheets at once
wo.Worksheets(MyArray).Copy before:=wn.Worksheets(1)

For Each so In wn.Worksheets
    'same effect as PasteSpecial>Values
    so.UsedRange.Value = so.UsedRange.Value
Next so

Application.DisplayAlerts = False
'delete last sheet, the default sheet in original workbook
'if there was more than one, need to adjust
wn.Worksheets(wn.Worksheets.Count).Delete
Application.DisplayAlerts = True
wn.SaveAs Filename:=ThisWorkbook.Path & "\" & "Report"
wn.Close savechanges:=True
End Sub