简体   繁体   English

将工作簿链接更改为新工作簿 VBA [Excel]

[英]Change Workbook links to New WorkBook VBA [Excel]

I'm creating a Macro that creates a new workbook and copies over a number of worksheets.我正在创建一个宏,它创建一个新工作簿并复制多个工作表。 Lets say we have the following worksheets:假设我们有以下工作表:

Names
Times
Lists

When pressing a the macro on the original workbook I want these work sheets copied over which I currently do perfectly fine.在原始工作簿上按下宏时,我希望复制这些工作表,我目前做得很好。 However, I don't understand how to make the links in these sheets refer to the new workbook rather than the original.但是,我不明白如何使这些工作表中的链接引用新工作簿而不是原始工作簿。

Code tried:代码尝试:

    Sub WorkBook_Test()
        Dim wbO As Workbook, wbN As Workbook
    
        Set wbO = ActiveWorkbook
        Set wbN = Workbooks.Add
    
        wbO.Sheets("Names").Copy wbN.Sheets(1)
        wbO.Sheets("Times").Copy wbN.Sheets(2)
        wbO.Sheets("Lists").Copy wbN.Sheets(3)
    
End Sub

Problem:问题:

The Lists sheet on the new workbook still refers to =[OrginalFile.xlsm]Names.B27 for example.例如,新工作簿上的 Lists 表仍然引用 =[OrginalFile.xlsm]Names.B27。 However I would like all links to refer to the current workbook rather than the original file.但是,我希望所有链接都引用当前工作簿而不是原始文件。

Note: I have some pretty in depth if statements for formulas so have multiple references that all refer to the original file when I would like the links to just reference the current files worksheets.注意:当我希望链接仅引用当前文件工作表时,我对公式有一些非常深入的 if 语句,因此有多个引用都引用原始文件。

Iterate over LinkSources and use the ChangeLink method.遍历LinkSources并使用ChangeLink方法。

Option Explicit

Sub WorkBook_Test()

    Dim wbO As Workbook, wbN As Workbook

    Set wbO = ActiveWorkbook
    Set wbN = Workbooks.Add

    wbO.Sheets("Names").Copy wbN.Sheets(1)
    wbO.Sheets("Times").Copy wbN.Sheets(2)
    wbO.Sheets("Lists").Copy wbN.Sheets(3)
    
    Dim ar, n As Integer
    With wbN
        ar = .LinkSources(1) 'xlExcelLinks
        If Not IsEmpty(ar) Then
            For n = 1 To UBound(ar)
                .ChangeLink Name:=ar(n), _
                    NewName:=.Name, Type:=xlExcelLinks
                'Debug.Print n, ar(n)
            Next
        End If
    End With

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM