Wednesday, February 6, 2008

Add a hyperlink to Excel using VBA

To add a hyperlink to a website using VBA, use the code below.

In summary, the syntax for adding a hyperlink is as follows and can be seen in the examples below:
  • Method: Worksheets("Sheet1").Hyperlinks.Add
  • Anchor: refers to the location where you want the hyperlink.
  • Address: refers to the web address (or document address) you want to hyperlink to
  • TextToDisplay: refers to what you want the text that holds the link to display. ( See bottom example if you want to keep the text that is already in the cell you are adding the link to)
'Adds a link to http://excelvbaprograms.blogspot.com/ in Row 1, Column A to text "Link me out"
Sub WebLink()
Worksheets("Sheet1").Hyperlinks.Add Anchor:=Cells(1, 1), Address:= _
"http://excelvbaprograms.blogspot.com/" _
, TextToDisplay:="Link me out" 'whatever you want the link text to display
End Sub

'Adds a link to http://excelvbaprograms.blogspot.com/ to text currently displayed in Row 1, Column A
Sub WebLink()
Worksheets("Sheet1").Hyperlinks.Add Anchor:=Cells(1, 1), Address:= _
"http://excelvbaprograms.blogspot.com/" _
, TextToDisplay:=Worksheets("Sheet1").Cells(1, 1).Value 'Will add a link to text currently in cell
End Sub

Note: Cells(1, 1) is in the format Cells(row, column) so, for example, column A is referred to by 1, Column B would be 2, Column C would be 3, etc.