使用VBA将整个Excel工作簿复制到另一个工作簿

时间:2013-01-31 04:33:31

标签: excel vba excel-vba

我有一个包含4个工作表的工作簿(“初始工作簿”) 我需要将所有四个工作表复制到另一个工作簿(“新工作簿”)。

我有以下代码,允许我从新工作簿导航到初始工作簿,然后在一个工作表上复制特定范围。我想修改它以允许我选择并复制原始工作表上的所有四个工作表。

非常感谢您提供的任何帮助:

Private Sub CommandButton1_Click()

    Dim wkbCrntWorkBook As Workbook
    Dim wkbSourceBook As Workbook

    Dim rngSourceRange As Range
    Dim rngDestination As Range

    Set wkbCrntWorkBook = ActiveWorkbook

    With Application.FileDialog(msoFileDialogOpen)
        .Filters.Clear
        .Filters.Add "Excel 2002-03", "*.xls", 1
        .Filters.Add "Excel 2007", "*.xlsx; *.xlsm; *.xlsa", 2
        .AllowMultiSelect = False
        .Show

        If .SelectedItems.Count > 0 Then
            Workbooks.Open .SelectedItems(1)
            Set wkbSourceBook = ActiveWorkbook
            Set rngSourceRange = Application.InputBox(prompt:="Select source range", Title:="Source Range", Default:="$A:$CS", Type:=8)
            wkbCrntWorkBook.Activate
            Set rngDestination = Application.InputBox(prompt:="Select destination cell", Title:="Select Destination", Default:="A1", Type:=8)
            rngSourceRange.Copy rngDestination
            rngDestination.CurrentRegion.EntireColumn.AutoFit
            wkbSourceBook.Close False
        End If
    End With

End Sub

3 个答案:

答案 0 :(得分:3)

答案 1 :(得分:2)

此重新编写的代码应复制您的工作表:

Private Sub CommandButton1_Click()
    Dim wkbSource As Workbook
    Dim wkbTarget As Workbook 'better use source and target as names, as its less confusing
    Dim strFileName As String

    Set wkbSource = ActiveWorkbook

    strFileName = Application.GetOpenFilename( _
        "Excel 2002-03 (*.xls), *.txt, " & _
        "Excel 2007 (*.xlsx; *.xlsm; *.xlsa), *.xlsx; *.xlsm; *.xlsa")

    If strFileName = "False" Then Exit Sub 'make sure that your locale also returns False!

    Set wkbTarget = Workbooks.Open(strFileName)
    wkbSource.Sheets(Array("Sheet1", "Sheet2", "Sheet3", "Sheet4")).Copy _
        Before:=wkbTarget.Sheets(1)
    'Further editing goes here

    wkbTarget.Close False

End Sub

只需根据您的需要更换工作表名称。

(PS:你可以自己找到这些命令,如果你只是记录一个宏,你将工作表复制到另一个工作簿 - 然后查看生成的代码!;-))

答案 2 :(得分:1)

我知道这是旧帖子,但是现有答案仅复制表格(不包括查询等),并且这样做的效率非常低。下面的代码对我来说就像一个魅力:

Function duplicateWorkbook(wk As Workbook) As Workbook
    Dim path As String
    path = Environ("temp") & "\" & wk.Name & "." & _ 
        Right(wk.FullName, Len(wk.FullName) - InStrRev(wk.FullName, "."))
    wk.SaveCopyAs path
    Set duplicateWorkbook = Workbooks.Add(path)
    Kill path
End Function

要使用,只需按以下方式调用它即可:

Dim wk AS Workbook: Set wk = duplicateWorkbook(ActiveWorkbook)

该代码将工作簿的临时副本保存在temp文件夹中,使用该临时簿作为模板创建一个新工作簿,然后删除该临时工作簿。