Shorten urls with bit.ly web API and VBA

Turns out you can shorten URLs easily with bit.ly. In More XMLHTTP Web API examples I mentioned that it was difficult, because bit.ly returns an XML document which must be parsed for the response.

Apparently bit.ly can also return just the shortened URL. So without further ado, here is the extremely short code that returns a shortened URL:

Function bitlyURL(txt As String) As String
' based on http://code.google.com/p/bitly-api/wiki/ApiDocumentation
  Dim xml As Object
  Set xml = CreateObject("MSXML2.XMLHTTP.6.0")

  xml.Open "POST", _
           "http://api.bit.ly/shorten?version=2.0.1&format=text&login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07&longUrl=" & _
           txt, False
  xml.Send

  bitlyURL = xml.responsetext
End Function

By specifying the format as text, we get only the shortened URL and none of that pesky XML. Note that the URL string requires a login and API key. I "borrowed" the demo information from the API documentation, so if the function stops working, you might need to register and get an API key.

Sample usage:

Sub tst()

Debug.Print bitlyURL("http://www.google.com")

End Sub

Download sample workbook

About JP

I'm just an average guy who writes VBA code for a living. This is my personal blog. Excel and Outlook are my thing, with a sprinkle of Access and Word here and there. Follow this space to learn more about VBA. Keep Reading »


Related Articles:


Share This Article:

Share and bookmark this articledelicious buttonfacebook buttonlinkedin buttonstumbleupon buttontwitter button

comment bubble 1 Comment(s) on Shorten urls with bit.ly web API and VBA:

  1. People use shortened urls way too much. Sure, in twitter you need them,otherwise the url takes up 2/3 of your message. But elsewhere, it's courteous to publish the entire url so a user knows where the click will lead.

This article is closed to any future comments.
Peltier Tech Charting Utilities for Excel