简体   繁体   中英

Update links between source and destination excel files

I have a folder that contains one excel source file and two excel destination files. My objective is to create a macro that updates the links in the destination files whenever the user saves the source file. I need this macro to be executed even when the destination files are closed because the user only opens the source file.

Add the following subroutine to a standard module in your source workbook:

Public Sub SaveDestinationFiles()
    Const N as Long = 2
    Dim strDest(1 To N) As String
    Dim wbDest As Workbook
    Dim i As Long

    ' Replace these with the actual shared drive & names of the destination folders & files
    strDest(1) = "D:\sharedfolder\dest1.xlsx"
    strDest(2) = "D:\sharedfolder\dest2.xlsx"

    Application.ScreenUpdating = False
    On Error Resume Next
    For i = 1 To N
        Set wbDest = Workbooks.Open(strDest(i), UpdateLinks:=True)
        If Err.Number = 0 Then
            wbDest.Save
            wbDest.Close
        ElseIf Err.Number = 1004 Then
            ' Delete this next line if you don't want to show any warning message when the save fails.
            MsgBox "Could not update " & strDest(i) & ". Please follow up to ensure this file is kept current.", vbExclamation, "Warning"
        End If
        Err.Clear
    Next i
    Application.ScreenUpdating = True
End Sub

Then, add the following subroutine to the ThisWorkbook code module in your source workbook:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    SaveDestinationFiles
End Sub

The first sub will simply open each destination workbook while allowing its links to update, save it, and close it--which should accomplish what you're looking to do. This happens without the user actually seeing those workbooks open, because of the lines with Application.ScreenUpdating .

The second sub is what makes the first sub fire automatically whenever someone saves the source workbook. This sub is an event procedure, so it's important not to change its name or arguments.

If the destination files are indeed in the same folder as the source file, then you can just put the filename as "whatever.xlsx". However, if they are in a different folder, then you should use the full name, eg "C:\otherfolder\whatever.xlsx" instead.

Finally, you can also easily extend the sub to add more destination files to be saved in the future, if you ever need to: for example, if you wanted to have 3 files, then change the first line to Const N as Long = 3 , and add strDest(3) = "dest3.xlsx" where the filenames are.

Hope this helps!

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