I'm trying to error-proof a spreadsheet at work. One thing we've had trouble with is people copy-pasting links then just changing the RMA number. This would work in theory if all the links had the same extension, but some are .xls and some are .xlsx.
I've made it so that when a cell in the RMA column is changed, the cell offset 53 to the right of it gets a hyperlink generated by the public function GetCRRLink() inserted into it.
Private Sub Worksheet_Change(ByVal ChangedCells As Range)
'Some code omitted here, RMA is defined
If Not Intersect(CurrentCell, RMA) Is Nothing Then
Set CurrentCell.Offset(0, 53).Formula = GetCRRLink(CurrentCell.Value)
End If
'Some code omitted here
End Sub
'Meanwhile, in Module 1
Public Function GetCRRLink(RMA As String) As Hyperlink
On Error Resume Next
Dim TryLink As Hyperlink
Set TryLink.TextToDisplay = "CRR Form"
Set TryLink.Address = "redacted" & RMA & ".xls"
TryLink.Follow
If Err.Number = 0 Then
GetCRRLink = TryLink
Exit Function
End If
Err.Clear
Set TryLink.Address = "redacted" & RMA & ".xlsx"
TryLink.Follow
If Err.Number = 0 Then
GetCRRLink = TryLink
Exit Function
End If
Set TryLink.TextToDisplay = "Error"
GetCRRLink = TryLink
End Function
When trying to set the TextToDisplay or Address properties of TryLink, I get "Compile error: Wrong number of arguments or invalid property assignment".
Worksheet_Changeevent handler (unless this is in a regular module and you're calling it from the sheet module event handler?) More significant - there is no such thing as a free-floating hyperlink object: you can only create one by adding it to a sheet' sHyperlinkscollection. So what you're trying to do here can't work the way you have it.Dir()to check if the file exists. If in a HTTP location you can use an XMLHTTP call to see if there's a matching resource at that URL.Hyperlinkobject, then add it to the sheet'sHyperlinksobject as the first or last element? Also with regards to your second comment, doesxmlhttpwork in excel vba? That sounds like it might be the best option.