简体   繁体   中英

Target one specific workbook among multiple workbooks

So I have this code to update links within my excel workbook

Dim alertTime As Date

Public Sub Refresh()
'refresh
ActiveWorkbook.UpdateLink (ActiveWorkbook.LinkSources)
'Workbooks("Requests").UpdateLink (Workbooks("Requests").LinkSources)
alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
    Application.OnTime alertTime, "Refresh"
Debug.Print Now() & " - Links Updated"

'MsgBox "5 Seconds have passed, refreshing", vbInformation, "Debug"

End Sub
Sub StopRefresh()
    Application.OnTime alertTime, "Refresh", , False
End Sub

The code works, but as soon as I open up another workbook and the refresh triggers and it errors out. I want to be able to target that specific workbook for the refresh command.

Any help is welcomed.

您可能需要将工作表也这样放置:

workbooks("Requests").Sheets("Sheetname").UpdateLink(Workbooks("Requests").Sheets("Sheetname").LinkSources)

Your statement ActiveWorkbook.UpdateLink (ActiveWorkbook.LinkSources) updates the link in the "Active" Workbook. That's the workbook that you are currently working on. When you open a new workbook, the new workbook becomes the active workbook.

Instead of ActiveWorkbook.UpdateLink (ActiveWorkbook.LinkSources) try this:

Workbooks("nameOfWorkbook").UpdateLink (Workbooks("nameOfWorkbook").LinkSources)

Where nameOfWorkbook is the filename of the workbook (ie, filename, extension and path if necessary) for which you want to update links. For example,

Workbooks("Requests.xlsb").UpdateLink (Workbooks("Requests.xlsb").LinkSources)

If the active directory is different than the directory in which Requests.xlsb is saved, then you must include the full path, like this:

Workbooks("C:\Users\yourID\Documents\Requests.xlsb").UpdateLink _
   (Workbooks("C:\Users\yourID\Documents\Requests.xlsb").LinkSources)

or more concisely:

With Workbooks("C:\Users\yourID\Documents\Requests.xlsb")
    .UpdateLink .LinkSources
End with

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