Showing posts with label Excel VBA. Show all posts
Showing posts with label Excel VBA. Show all posts

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.

Thursday, January 24, 2008

Excel VBA: Moving a Shape to Specific Position

To move a shape to a specific position of an excel workbook, you can specify the location of the shape's top, left corner by using the following commands:

ActiveSheet
.shapes(X).top = 100
ActiveSheet.shapes(X).left = 200

Each shape is referred to by a number so replace the X by that number. the first shape up is numbered 1, the second is numbered 2 and so on. The code for shape 1 would look like:

ActiveSheet.shapes(1).top = 100
ActiveSheet.shapes(1).left = 200


Each shape is also given a name such as "Rectangle 1" so an alternative to this code is:

ActiveSheet.shapes("Rectangle 1").top = 100
ActiveSheet.shapes(
"Rectangle 1").left = 200

Now, as far as exactly where the shapes will be located, you will likely have to play around with it to get it right, the location does not appear to correspond with pixels or cell locations, so just try different numbers and see where it ends up!

I will post code soon that will allow a user to identify a shape's name by clicking it. Leave a comment and I will likely post it sooner. In the meantime, you can record a macro to get the shapes name or keep track of the order in which you added the shapes so you can refer to them by number (or by "Rectangle 1" for the first rectangle you add, "Rectangle 2" for the second, etc.)