简体   繁体   中英

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. 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.

Iterate over LinkSources and use the ChangeLink method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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