Use the VBA ShellExecute function to open a URL in the default browser. There are many examples online showing how to open a website in internet explorer, but the VBA ShellExecute function lets you open URLs in your default browser - whether it’s Chrome, Firefox, or some other more exotic browser. Isn’t that great!?
This macro example even has a filter to handle the most common form of the ShellExecute Access Denied error.
VBA Open URL in Default Browser
Option Explicit Private Declare Function ShellExecute _ Lib "shell32.dll" _ Alias "ShellExecuteA" ( _ ByVal hwnd As Long, _ ByVal lpOperation As String, _ ByVal lpFile As String, _ ByVal lpParameters As String, _ ByVal lpDirectory As String, _ ByVal nShowCmd As Long) _ As Long Private Sub LaunchWebsite(strUrl As String) On Error GoTo wellsrLaunchError Dim r As Long r = ShellExecute(0, "open", strUrl, 0, 0, 1) If r = 5 Then 'if access denied, try this alternative r = ShellExecute(0, "open", "rundll32.exe", "url.dll,FileProtocolHandler " & strUrl, 0, 1) End If Exit Sub wellsrLaunchError: MsgBox "Error encountered while trying to launch URL." & vbNewLine & vbNewLine & "Error: " & Err.Number & ", " & Err.Description, vbCritical, "Error Encountered" End Sub
Like I said, it’s pretty common for ShellExecute to generate an “Access Denied” error for some folk when they try to launch a URL. When that happens, this macro attempts to execute an alternate form of the ShellExecute function.
The error code associated with the access denied error, SE_ERR_ACCESSDENIED, is 5. This macro attempts to explicitly call the rundll32.exe FileProtocolHandler when this error code is encountered so you can seemlessly launch your websites.
Here’s an example of how to call the LaunchWebsite macro to open up my lovely home page:)
Sub URLdemo() LaunchWebsite ("http://wellsr.com/") End Sub
I hope you enjoyed this Code Library macro example! Let’s have a discussion in the comments section!
Please subscribe to my email list, share this article on social media and follow me on Google+ and Twitter for more great VBA content!