我使用下面的代码将工作表从源工作簿复制到数百个目标工作簿。源工作表包含对源工作簿中其他工作表的引用(以公式形式);我想将这些引用保留在工作表之间,但保留在目标工作簿中。可以修改此代码来执行此操作吗?
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/