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

标签 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

最佳答案

尝试这样的事情:

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

我通过在目标工作簿处于事件状态并打开宏记录器的情况下转到数据>编辑链接,选择“更改源”,然后浏览到目标工作簿来获得此信息。

关于excel - 将工作表复制到多个工作簿时更改引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53435972/

相关文章:

sql - 如何自动化此日期代码,这样我就不必每年都更改它?

c# - 将数据导出到 excel 时应用程序停止

excel - 使用Excel VBA在网页上的复选框

internet-explorer - 哪个 .dll 包含 HTMLElement 类?

Excel 打印带有正确小数分隔符的数字

algorithm - VBA以相反的顺序逐行读取大文本文件

excel - Excel 中的完整超链接路径

excel - 如何根据接收时间对邮件应用过滤器?

java - 更改路径后,VB 脚本未执行 我看到 Windows 脚本主机提示符具有不同的路径

excel - 用于 64 位 Visual Basic 的更新