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
Make powerful macros with our free VBA Developer Kit Tutorials like this can be complicated. That’s why we created our free VBA Developer Kit and our Big Book of Excel VBA Macros to supplement this tutorial. Grab them below and you’ll be writing powerful macros in no time.
Tutorials like this can be complicated. That’s why we created our free VBA Developer Kit and our Big Book of Excel VBA Macros to supplement this tutorial. Grab them below and you’ll be writing powerful macros in no time.
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! When you’re ready to take your VBA to the next level, subscribe using the form below.