How to find location of link in Excel workbook? - vba

I have an Excel book that, when opened, gives the warning:
This workbook contains links to other data sources.
I want to remove all of these links so that the warning will not be triggered. Thinking that any external link will be of the form '[workbook path]'!address I used this code:
Sub ListLinks()
Dim wb As Workbook
Dim link As Variant
Set wb = ThisWorkbook
For Each link In wb.LinkSources(xlExcelLinks)
Debug.Print link
Next link
End Sub
This returned a file path:
\\somePath\xyz\aWorkbook.xlsm
I searched all formulas in the workbook for this string using Ctrl+F, but no results were returned. How do I find and remove this link?

Your workbook could be linking via a named range pointing to another workbook. A search of formulas for the linked workbook may find nothing because the link is hidden in the name.
Check your named ranges for links to other workbooks.

Breaking the links is not enough to suppress the warning. On the Edit Links window, I clicked Startup Prompt and set the radio button to "Don't display the alert and don't update automatic links". This successfully prevented the warning from appearing.

The following loop should work.
Dim intCounter As Integer
Dim varLink As Variant
'Define variable as an Excel link type.
varLink = ActiveWorkbook.LinkSources(Type:=xlLinkTypeExcelLinks)
'Are there any links?
If IsArray(varLink) = False Then
Exit Sub
End If
'Break the links in the active workbook.
For intCounter = 1 To UBound(varLink)
ActiveWorkbook.BreakLink _
Name:=varLink(intCounter), _
Type:=xlLinkTypeExcelLinks
Next intCounter

I had this problem after removing all the links as described above, I then found that some of my validation data was refering to other workbooks. After correcting this the problem disappeared.

Could be in one of these?:
HYPERLINKS (formula and normal)
NAME MANAGER
VALIDATION
CONDITIONAL FORMATTING
BUTTON WITH MACRO (still pointing to originating macro)

Related

VBA is skipping code when a userform reference is reached? Attempting to write to another wbk

I'm using a userform to collect data and add it to an empty line in a workbook.
Structure of code is as follows:
Main sub s_OpenWriteToTargetFile is called from userform mainForm.
It checks availability of the target workbook.
It opens the target workbook.
It calls sub "s_WriteLines". Everything is OK up to this point.
Sub s_WriteLines should load textbox values from mainForm into various variables and paste them into the target workbook.
For some reason, code execution jumps out of s_WriteLines as soon as it reaches With MainForm..., and it returns to the mother sub.
s_WriteLines sub
Sub s_WriteLines
Dim a,b as integer
With mainForm
a = .tb_a.Value
b = .tb_b.Value
End With
End Sub
I can't wrap my head around it. Does this have something to do with the modality of the userform?
As AcsErno suggested in the comments, there was a on error resume next that I didn't notice, and it kept me from learning that the form is failing to load a rowsource property of a combobox.
The rowsource was specified as follows:
mainForm.cb_Wiresize.RowSource = wiresizesWSheet.Name & "!" & wiresizesFinalRange.Address
The workbook that is opened to be written in also becomes active, and then the range that I specified as rowsource refers to a worksheet that doesn't exist - because I specified it only as "worksheet + range", instead of "workbook + worksheet + range".
To expand on my question, how can I refer to the specific workbook object using the syntax posted above? I tried different formulations but none worked.

Excel VBA macro - Change link name

I have a excel macro routine that I need to prep a file for another routine which is run daily. This prepping involves changes the links of t-1 file to a t0 file.
The code I usually do is:
ActiveWorkbook.ChangeLink Name:= _
"file path", NewName:=new_file_path, Type:=xlExcelLinks
My trouble now is that for this particular routine the file path to be changed to a new routine is not always the same, thus I would need a way to automatize finding out what are the current links to replace them all. The new file path I now because it is the worksheet that is calling this routine and opening this file, so first thing I do Is
new_file_path = "C:\...."& ActiveWorkbook.Name & ".xlsm"
What would help me is if there is a trick to replace all links for a new one, without the need to say the name/path of the old links. Does any one know?
Thanks
To change all the excel links in a workbook try this procedure:
Sub WbThs_ChangeLink_Excel()
Dim wbTrg As Workbook
Dim sLinkNew As String
Dim aLinks As Variant, vLink As Variant
sLinkNew = "##VBA Links Replace - Target 3.xlsb" 'Change as required
Set wbTrg = ThisWorkbook 'Change as required
Rem Set array with all excel links
aLinks = ActiveWorkbook.LinkSources(xlExcelLinks)
Rem Replace each excel Link
If Not IsEmpty(aLinks) Then
For Each vLink In aLinks
wbTrg.ChangeLink Name:=vLink, NewName:=sLinkNew, Type:=xlExcelLinks
Next: End If
End Sub
See the following pages for additional information on the resources used:
Workbook.ChangeLink Method (Excel)
Workbook.LinkSources Method (Excel)
XlLink Enumeration (Excel)

Copy from a workbook to another workbook

I am having issues developing this code. I was able to develop the code to copy new data from my workbook to an existing path but am running into issues when trying to retrieve data from the existing path work book.
The concept is that there is a workbook in my system that will be collecting data. The data comes from different users that are working on project information. Once they have completed the project this new information along with existing information gets uploaded back to the workbook collecting that data. The work book collecting the data will always have a defined path. The workbooks that users are working off of will be in multiple places across the system.
The below macro keeps failing on the "Organizer.Sheets("Partnumber_Vendor_Database").Select". I am unsure why.
"Organizer" is the local database the user will use.
"Partnumber_Vendor_File" is the local database the information is stored.
If you can see that this code could be developed better please let me know! :)
Sub Find_Partnumber_Vendor_File()
' This sub is to open the partnumber_Vendor file to update the local database.
On Error Resume Next
Dim Organizer As Workbook
Set Organizer = Application.ActiveWorkbook
Dim Partnumber_Vendor_File As Workbook
Set Partnumber_Vendor_File = Workbooks.Open("S:\Supply Chain\PURCHASING\Forms and Templates\BOM Organizer\Partnumber_Vendor_File.xlsx")
If Err.Number = 1004 Then
MsgBox "Could not open. Check path in VBA"
Exit Sub
End If
If Partnumber_Vendor_File.ReadOnly Then
MsgBox "Sorry, partnumber to vendor database was already in use, try later"
Exit Sub
End If
On Error GoTo 0
Dim Data As Long
Data = ActiveSheet.Cells(Rows.count, 1).End(xlUp).Row
Range("A1:" & "D" & Data).Copy
Organizer.Sheets("Partnumber_Vendor_Database").Select
Range("A1:D1").Select
Selection.Insert Shift:=xlDown
Partnumber_Vendor_File.Close
End Sub
Althoug it is easy to use, avoid ActiveWorkbook, ActiveSheet and Sheets(<Title of the Sheet.).
The problem with the first two is that is hard to tell if the activeworkbook is actually the workbook you are looking for, specially when there are more than 1 workbook open. To workaround this, one solution is the use the Workbooks object to select the correct work book by its NAME (property CodeName). The Same for the Sheets, change the REAL NAMES of the Sheets so you can properlly call them.
The third is basically the same principle. In general, do not use titles of Sheets as references, use the REAL NAME of the object. Use the Property window in the VBA code to change that.
The error may come from 2 situations:
1 - Your selected workbook is not the actual workbook you want to work on.
2 - The Sheet "Partnumber_Vendor_Database" had its title changed or miswritten.
Hope it helps.

Excel VBA Allow user to select an already open workbook and attach variables to selected workbook

With Excel 2013 VBA, I am familiar with setting the value of a Workbook variable with:
Set oWBSource = Workbooks.Open(strFileToOpen) 'Works well.
In my situation though, sometimes the Workbook is already open on the desktop. I am trying to find a more elegant way to "select" that spreadsheet and then attach my variable to that workbook to operate on. The code is running on a separate "master" spreadsheet.
Currently, I am asking the user if the file is already open. If so, then:
Dim rng As Range
Set rng = Application.InputBox("Select any cell on workbook to operate on.", "Click Workbook Cell", Type:=8) 'Stops code and allows user to select a cell on an open spreadsheet
Dim sTest As String 'variable used to test.
sTest = ActiveCell.Value 'Testing to see what value code is seeing.
sTest = ActiveWorkbook.Name 'Testing to see what value code is seeing
Set oWBSource = Workbooks(ActiveWorkbook.Name) 'Works if selected Workbook is maximized and minimized.
If I run the above code and when it runs the inputbox, if I click one cell on the spreadsheet I want the code to operate on and allow the code to continue, the variables still reference the Workbook where the code resides rather than the "selected" workbook. If, while selecting one cell, I also maximize and minimize the spreadsheet (basically Activate it) and then click a cell and allow the code to continue, the active spreadsheet is set and it seems to work. I realize the cell reference is doing nothing. But the pause allows me to "Activate" the desired spreadsheet.
I am looking for a more elegant way to handle attaching my code to an already open spreadsheet. My current solution is clunky. Isn't there a way to have the user select the open spreadsheet and then have my code "act" on that spreadsheet?
I know this is a weird question. Be kind rating it please??!!
If I understand correctly what you're trying to do, just use the rng to resolve the selected Workbook:
Set oWBSource = rng.Parent.Parent
rng.Parent is the Worksheet a Range is a part of, and the .Parent of a Worksheet is its Workbook.

Update linked fields in Word document from Excel VBA

I am trying to automatically update certain information (such as names, dates and numbers) across 3 different Word documents by putting the data into a spreadsheet and linking to the respective cells from Word. The spreadsheet has some Macros in it which auto-update parts of the spreadsheet internally.
Everything is working fine, except for updating the links in the Word documents.
When trying to update a link in Word by right-clicking on it and selecting the "update link" option it brings up the Macro warning dialog for the spreadsheet, asking whether I want to activate Macros or not. It doesn't do this just once but constantly during the 20s or so the update process takes (which seems unusually long to me). So updating the link works, but only if you're willing to click the "activate Macros" button of a few dozen times.
I tried to automate updating all fields in a document from Word with VBA, but that has the same problem, it also brings up the Macros dialog constantly for half a minute.
Here's my code for that:
Sub UpdateFields()
ActiveDocument.Fields.Update
End Sub
I also tried to update the Word documents directly from the spreadsheet, but that does not work either, because when Excel tries to open a Word document via VBA the program stops executing and trows this error:
"Excel is waiting for another application to complete an OLE action."
Clicking ok and waiting does not help because the error message reappears after a few seconds, and the only way to stop it is to manually kill the Excel process.
Here's my Excel Macro code:
Sub LoopThroughFiles()
Path = Application.ActiveWorkbook.Path
Dim WordFile As String
WordFile = Dir(Path & "\*.doc")
Do While Len(WordFile) > 0
Run Update(Path & "\" & WordFile)
WordFile = Dir
Loop
End Sub
Function Update(Filepath As String)
Dim WordDoc As Word.Document
Set WordApplication = CreateObject("Word.Application")
Set WordDoc = WordApplication.Documents.Open(Filepath) 'This produces the error
ActiveDocument.Fields.Update
End Function
Note that the only files in the folder are the 3 documents and the spreadsheet, and the program does find the files without any problems.
I have searched for solutions online but I did not really find anything, which I found odd, since it seems like a pretty common thing that someone would do with VBA.
Then again, I have very little experience with VBA, so I might be completely missing the point and there is a super simple solution I am just not aware of.
I think I see the error, which is a silent failure, becuase the document contains links, there is an open dialog waiting for you to say "yes" or "no" to update the links.
We can suppress this dialog by disabling the automatic link updates (WordApplication.Options.UpdateLinksAtOpen = False).
Function Update(Filepath As String)
Dim WordApplication As Word.Application
Dim WordDoc As Word.Document
Dim updateLinks As Boolean
Set WordApplication = CreateObject("Word.Application")
updateLinks = WordApplication.Options.UpdateLinksAtOpen 'capture the original value
WordApplication.Options.UpdateLinksAtOpen = False 'temporarily disable
Set WordDoc = WordApplication.Documents.Open(Filepath)
WordDoc.Fields.Update
'MsgBox "Links updated in " & WordDoc.Name
'## Save and Close the Document
WordDoc.Save
WordDoc.Close
'## reset the previous value and Quit the Word Application
WordApplication.Options.UpdateLinksAtOpen = updateLinks '
WordApplication.Quit
End Function
Also, remember to Save and Close the document, and Quit the word application inside the function.
I made this other modification:
In your function, ActiveDocument is not an object in Excel, so you would need to qualify it, otherwise that line will also throw an error. Rather than refer to WordApplication.ActiveDocument, I just simply refer to the WordDoc which you have already assigned.