将工作表复制到多个工作簿时更改引用

时间:2018-11-22 17:38:10

标签: excel vba excel-vba

我正在使用下面的代码将工作表从源工作簿复制到几百个目标工作簿。源工作表包含对源工作簿中其他工作表的引用(按公式);我想在工作表之间保留这些引用,但要保留在目标工作簿中。可以修改此代码来做到这一点吗?

Option Explicit

Public Sub CopySheetToAllWorkbooksInFolder()

    Dim sourceSheet As Worksheet
    Dim folder As String, filename As String
    Dim destinationWorkbook As Workbook

    'Worksheet in active workbook to be copied as a new sheet to the destination workbook

    Set sourceSheet = ActiveWorkbook.Worksheets("Edit")

    'Folder containing the destination workbooks

    folder = "M:\Employee Information\Peter Young\Msc Project\1 - 181028 - Office First Floor\MacroCopy\"

    filename = Dir(folder & "*.xlsx", vbNormal)
    While Len(filename) <> 0
        Debug.Print folder & filename
        Set destinationWorkbook = Workbooks.Open(folder & filename)
        sourceSheet.Copy before:=destinationWorkbook.Sheets(1)
        destinationWorkbook.Close True
        filename = Dir()  ' Get next matching file
    Wend
End Sub

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

Public Sub CopySheetToAllWorkbooksInFolder()

    Dim sourceWorkbook As Workbook
    Dim sourceSheet As Worksheet
    Dim destinationWorkbook As Workbook
    Dim folder As String, filename As String

    'Worksheet in active workbook to be copied as a new sheet to the destination workbook
    Set sourceWorkbook = ActiveWorkbook
    Set sourceSheet = sourceWorkbook.Worksheets("Edit")

    'Folder containing the destination workbooks

    folder = "M:\Employee Information\Peter Young\Msc Project\1 - 181028 - Office First Floor\MacroCopy\"

    filename = Dir(folder & "*.xlsx", vbNormal)
    While Len(filename) <> 0
        Debug.Print folder & filename
        Set destinationWorkbook = Workbooks.Open(folder & filename)
        sourceSheet.Copy before:=destinationWorkbook.Sheets(1)
        destinationWorkbook.ChangeLink Name:=sourceWorkbook.Name, NewName:=destinationWorkbook.Name, Type:=xlExcelLinks
        destinationWorkbook.Close True
        filename = Dir()  ' Get next matching file
    Wend
End Sub

通过在目标工作簿处于活动状态且宏记录器已打开的情况下转到“数据”>“编辑链接”,选择“更改源”,然后浏览到目标工作簿,即可实现这一点。