Apologies if this question is elementary, i'm not great at VBA. I have 3 separate codes that i want to run one after the other at the click of a button. So i have the master code titled UpdateLinks that is supposed to call them. The first 2 (PreSelect & UpdateLinksCode)run the 3rd (PostSelect) doesn't. Individually they all work.
The purpose is to update links to external excel workbooks without having to manually enter the password. That is what the UpdateLinksCode macro is for. However, if the linked source does not require a password the UpdateLinksCode will drop the password in whatever cell was selected before running. Hence the PreSelect & PostSelect - supposed to delete the password and prevent exposure.
This is the master code:
Sub UpdateLinks()
Call PreSelect
Call UpDateLinksCode
Call PostSelect
End Sub
The individual ones are as below:
Sub PreSelect()
Sheets("Sheet1").Select
Range("A1").Select
End Sub
Sub UpDateLinksCode()
Const PWord As String = "password"
Dim xlLinks
Dim i As Integer
xlLinks = ThisWorkbook.LinkSources(xlExcelLinks)
If Not IsEmpty(xlLinks) Then
For i = 1 To UBound(xlLinks)
SendKeys PWord & "{Enter}"
ThisWorkbook.UpdateLink Name:=xlLinks(i)
Next i
End If
End Sub
Sub PostSelect()
Sheets("Sheet1").Select
Range("A1").Select
Selection.ClearContents
End Sub
It seems simple but i can't hack it.
Update: Appreciate all the input. I've now changed the code to sit in a module and refer to the worksheet by name. I've removed the call functions and separate codes and condensed it to the one. There are no errors when debugging or running through step by step.
However, same issue exists in that no further code will run following the 'send keys''. The "Range("A1").Select" needs to be in there because, something to do with the timing of the password request box popping up and the send keys inputting the password, causes half of the password to be typed into whichever cell is highlighted when the code is run. Therefore, i force it into cell A1 which has both background and text set to white.
Current code is as below:
Sub Update_links()
Worksheets("Staff Rota 2019").Unprotect "broncko"
Range("A1").Select
Dim PWord As String
PWord = "stevefinnan"
SendKeys PWord & "{Enter}"
ActiveWorkbook.UpdateLink Name:= _
"Y:\a - Staff Rota\Staff Rota 2019.xlsm", _
Type:=xlExcelLinks
Worksheets("Staff Rota 2019").Protect "broncko", DrawingObjects:=True,
Contents:=True, Scenarios:=True
end sub