如何从主工作簿复制并将数据粘贴到多个工作簿

时间:2019-02-14 09:04:00

标签: excel vba

我录制了一个宏,以将其从主工作簿复制并粘贴到另一个工作簿(我们称其为wbk1),但是我无法将其用于需要格式化的所有其他工作簿,因为该宏中的代码专门针对wbk1。

如何编写代码以使其引用当前打开的工作簿和主工作簿。

我试图声明并引用活动的工作簿,但是它会复制并粘贴到主工作簿上

Windows("master.xlsm").Activate
Selection.Copy

Dim WbkCurrent As Workbook
Set WbkCurrent = ActiveWorkbook
WbkCurrent.Activate
Range("A1").Select
ActiveSheet.Paste

我希望将数据粘贴到与主工作簿一起打开的其他任何工作簿上。

2 个答案:

答案 0 :(得分:0)

Windows("master.xlsm").Activate
Selection.Copy

Dim WbkCurrent As Workbook
Set WbkCurrent = ActiveWorkbook
Dim wb As Workbook

For Each wb In Application.Workbooks
  If wb.Name <> WbkCurrent.Name Then
      'For the codeline below: assuming that you want to paste your selection to the first sheet for each wb. 
      'Else, change worksheets number to the sheet you want to copy to or change 
      'Worksheets(1)' into 'Activesheet' to copy on the currently active sheet for each wb.
      wb.Worksheets(1).Range("A1").PasteSpecial (xlPasteAll)

  End If
Next wb

答案 1 :(得分:0)

从主书复制

这会将名为cMastermaster.xlsm)的工作簿的当前选择复制到其他每个打开的工作簿cRange的单元格A1ActiveSheet)中

代码

Option Explicit

Sub CopyFromMaster()

    Const cMaster As String = "master.xlsm"   ' Master Workbook
    Const cRange As String = "A1"             ' Paste Cell Range

    Dim wb As Workbook  ' Current Workbook

    ' Loop through all open workbooks.
    For Each wb In Workbooks
        ' Check if the name of the Current Workbook is different than the name
        ' of the Master Workbook.
        If wb.Name <> cMaster Then
            ' Copy the selection in Master Workbook to Paste Cell Range
            ' in ActiveSheet of Current Workbook.
            Windows(cMaster).Selection.Copy wb.ActiveSheet.Range(cRange)
        End If
    Next

End Sub

编辑

评论问题

“我将如何重复相同的指令,但是现在要从主工作簿的工作表2复制并粘贴到另一个打开的工作簿的工作表2中?”

Sub CopyFromMaster2()

    Const cMaster As String = "master.xlsm"   ' Master Workbook
    Const cRange As String = "A1"             ' Paste Cell Range

    Dim wb As Workbook  ' Current Workbook

    For Each wb In Workbooks
        ' Check if the name of the Current Workbook is different than the name
        ' of the Master Workbook.
        If wb.Name <> cMaster Then
            ' Before using selection (select) you have to make sure that
            ' the worksheet is active or just activate it.
            Workbooks(cMaster).Worksheets("Sheet2").Activate
            ' Copy the selection in "Sheet2" of Master Workbook to
            ' Paste Cell Range "Sheet2" of Current Workbook.
            Selection.Copy wb.Worksheets("Sheet2").Range(cRange)
        End If
    Next

End Sub