Nick
Nick

Reputation: 775

Select each cell in range VBA to activate hyperlinks

I have a column in excel which contains a mix of hyperlinks, empty cells and non hyperlinks.

Manually I can press F2 and enter. This selects the highlighted cell, activates if a hyperlink is present and then moves onto the next one ready to repeat.

I wish to create a macro in VBA that achieves this however so far I can only get the cells to select but it does not active the hyperlink if present.

I appreciate it is possible to format the cells in excel as hyperlinks but this again only seems to create the illusion they have been activated (blue and underlined) i.e. they aren't clickable.

Attempt so far:

Sub Macro2()

Dim c As Excel.Range
     
    For Each c In Selection
    
    c.Select
    Debug.Print c.Value
    ActiveCell.FormulaR1C1 = c.Value

    Next c

Desired (iterate through each selected range of cells)

enter image description here

Upvotes: 1

Views: 839

Answers (1)

Horaciux
Horaciux

Reputation: 6477

This should work, I added an URL validation from another SO answer.

Sub Macro1()

Dim c As Excel.Range
Dim url As String
    For Each c In Selection
    
    c.Select
    Debug.Print c.Value
    url = trim(CStr(c.Text))
    
    If Left(url, 4) <> "http" Then
        
        url = "http://" & url
    End If
    
    If URLExists(url) Then
         
        ActiveSheet.Hyperlinks.Add Anchor:=c, Address:=url, TextToDisplay:=c.Text
    End If
 Next c

 
End Sub


Function URLExists(url As String) As Boolean
    Dim Request As Object
    Dim ff As Integer
    Dim rc As Variant

    On Error GoTo EndNow
    Set Request = CreateObject("WinHttp.WinHttpRequest.5.1")

    With Request
      .Open "GET", url, False
      .Send
      rc = .StatusText
    End With
    Set Request = Nothing
    If rc = "OK" Then URLExists = True

    Exit Function
EndNow:
End Function

enter image description here

Upvotes: 0

Related Questions