49

How do I open an HTML page in the default browser with VBA? I know it's something like:

Shell "http://myHtmlPage.com"

But I think I have to reference the program which will open the page.

ashleedawg
  • 20,365
  • 9
  • 72
  • 105
dmr
  • 21,811
  • 37
  • 100
  • 138

6 Answers6

63

You can use the Windows API function ShellExecute to do so:

Option Explicit

Private Declare Function ShellExecute _
  Lib "shell32.dll" Alias "ShellExecuteA" ( _
  ByVal hWnd As Long, _
  ByVal Operation As String, _
  ByVal Filename As String, _
  Optional ByVal Parameters As String, _
  Optional ByVal Directory As String, _
  Optional ByVal WindowStyle As Long = vbMinimizedFocus _
  ) As Long

Public Sub OpenUrl()

    Dim lSuccess As Long
    lSuccess = ShellExecute(0, "Open", "www.google.com")

End Sub

As given in comment, to make it work in 64-bit, you need add PtrSafe in the Private Declare Line as shown below:

Private Declare PtrSafe Function ShellExecute _

Just a short remark concerning security: If the URL comes from user input make sure to strictly validate that input as ShellExecute would execute any command with the user's permissions, also a format c: would be executed if the user is an administrator.

Community
  • 1
  • 1
Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
  • 14
    Just a note for anyone who might use this in the future: You have to put the ShellExecute function at the top of the page, in the declarations section. – dmr Jul 02 '10 at 14:42
  • 11
    Some may need to add "PtrSafe" in the declare statement: "Private Declare PtrSafe Function ShellExecute..." to make it work in 64bit. – Jroonk Oct 30 '15 at 01:25
  • 1
    @ashleedawg: Note that `ThisWorkbook` only works in Excel – Dirk Vollmar Sep 25 '18 at 22:05
  • 3
    @Dirk - correct. You would send, for example, `application.followhyperlink` in Access or Project, `activedocument.followhyperlink` in Word, `activepresentation.folllowhyperlink` in PowerPoint, etc... Don't misunderstand, there's nothing wrong with your method; both are good choices for different situations. I'd be more likely to use `FollowHyperlink` for a one-off or situations where I need more control over the post/get/etc, and `ShellExecute` for groups of pages to be opened simultaneously. – ashleedawg Sep 25 '18 at 22:58
  • I tried the above in Mac and didn't work. I got a "file not found" error. I am guessing it's for the shell32.dll. Any idea how to get it to work in both Mac and Windows? Thanks. – Si8 May 06 '19 at 13:55
  • 2
    `ThisWorkbook.FollowHyperlink("http://www.yoursite.com")` worked for more. – Si8 May 06 '19 at 13:58
  • Any recommendations on how to validate the input for `ShellExecute` to avoid executing commands other than opening a URL in the default browser? Is simply checking for a prefix of "http://" or "https://" sufficient? – ChrisB Jun 07 '21 at 19:56
  • How to turn this into a function that only executes when a user clicks an excel cell with the troubling url? – Diego Oct 27 '21 at 17:37
54

You can even say:

FollowHyperlink "www.google.com"

If you get Automation Error then use http://:

ThisWorkbook.FollowHyperlink("http://www.google.com")
Kashyap
  • 15,354
  • 13
  • 64
  • 103
Rahul Narkhede
  • 541
  • 4
  • 2
  • 10
    If in Excel, you need a workbook object, like ThisWorkbook.FollowHyperlink "www.google.com" – Dick Kusleika Jun 14 '12 at 19:59
  • I was receiving Automation Error. So I needed to use `http://`. Then, the full command is: `ThisWorkbook.FollowHyperlink "http://www.google.com.br"` – Daniel Bonetti Jan 08 '15 at 19:04
  • 1
    This is simplest if you are accessing a trusted webpage, but if you want to open a powerpoint or pdf document into a web browser, you must use the ShellExecute by Dirk Vollmar to avoid an error message everytime you run it. – Jroonk Oct 30 '15 at 01:27
  • 2
    FollowHyperlink is messing with IE/Edge security, The solution using ShellExecute is more reliable as far as I have experienced – Cyprien Autexier Jun 14 '16 at 14:43
  • One problem with FollowHyperlink is that it is trying to interpret the url. If Url returns 404 VBA code fails. – Martin Kunc May 09 '17 at 16:44
  • How to close the browser window opened by FollowHyperlink? – Ujwal Ratra Oct 06 '17 at 05:58
  • although this solution works.. the accepted solution before this opens the browser with quick response. this solution is slightly slower to open the browser. – ihightower Nov 11 '17 at 18:46
  • re: @ihightower's comment: This `FollowHyperlink` method returns control to VBA faster than `ShellExecute`, but `ShellExecute` opens the pages *sllightly* faster overall, and requires an API. Also, the [`Workbook.FollowHyperlink` Method](https://learn.microsoft.com/office/vba/api/excel.workbook.followhyperlink) has more web-specific options. – ashleedawg Sep 25 '18 at 08:45
  • ShellExecute can be far faster for https connections as it seems to reuse credentials, whereas FollowHyperlink can trigger reauthorisation processes. – Michael Jun 17 '19 at 04:08
  • 1
    Just for information, this works with mailto: syntax to send mail. – Eneas Gesing Aug 06 '22 at 23:39
8

If you want a more robust solution with ShellExecute that will open ANY file, folder or URL using the default OS associated program to do so, here is a function taken from http://access.mvps.org/access/api/api0018.htm:

'************ Code Start **********
' This code was originally written by Dev Ashish.
' It is not to be altered or distributed,
' except as part of an application.
' You are free to use it in any application,
' provided the copyright notice is left unchanged.
'
' Code Courtesy of
' Dev Ashish
'
Private Declare Function apiShellExecute 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

'***App Window Constants***
Public Const WIN_NORMAL = 1         'Open Normal
Public Const WIN_MAX = 3            'Open Maximized
Public Const WIN_MIN = 2            'Open Minimized

'***Error Codes***
Private Const ERROR_SUCCESS = 32&
Private Const ERROR_NO_ASSOC = 31&
Private Const ERROR_OUT_OF_MEM = 0&
Private Const ERROR_FILE_NOT_FOUND = 2&
Private Const ERROR_PATH_NOT_FOUND = 3&
Private Const ERROR_BAD_FORMAT = 11&

'***************Usage Examples***********************
'Open a folder:     ?fHandleFile("C:\TEMP\",WIN_NORMAL)
'Call Email app:    ?fHandleFile("mailto:dash10@hotmail.com",WIN_NORMAL)
'Open URL:          ?fHandleFile("http://home.att.net/~dashish", WIN_NORMAL)
'Handle Unknown extensions (call Open With Dialog):
'                   ?fHandleFile("C:\TEMP\TestThis",Win_Normal)
'Start Access instance:
'                   ?fHandleFile("I:\mdbs\CodeNStuff.mdb", Win_NORMAL)
'****************************************************

Function fHandleFile(stFile As String, lShowHow As Long)
Dim lRet As Long, varTaskID As Variant
Dim stRet As String
    'First try ShellExecute
    lRet = apiShellExecute(hWndAccessApp, vbNullString, _
            stFile, vbNullString, vbNullString, lShowHow)

    If lRet > ERROR_SUCCESS Then
        stRet = vbNullString
        lRet = -1
    Else
        Select Case lRet
            Case ERROR_NO_ASSOC:
                'Try the OpenWith dialog
                varTaskID = Shell("rundll32.exe shell32.dll,OpenAs_RunDLL " _
                        & stFile, WIN_NORMAL)
                lRet = (varTaskID <> 0)
            Case ERROR_OUT_OF_MEM:
                stRet = "Error: Out of Memory/Resources. Couldn't Execute!"
            Case ERROR_FILE_NOT_FOUND:
                stRet = "Error: File not found.  Couldn't Execute!"
            Case ERROR_PATH_NOT_FOUND:
                stRet = "Error: Path not found. Couldn't Execute!"
            Case ERROR_BAD_FORMAT:
                stRet = "Error:  Bad File Format. Couldn't Execute!"
            Case Else:
        End Select
    End If
    fHandleFile = lRet & _
                IIf(stRet = "", vbNullString, ", " & stRet)
End Function
'************ Code End **********

Just put this into a separate module and call fHandleFile() with the right parameters.

dan
  • 3,439
  • 17
  • 54
  • 82
6

I find the most simple is

shell "explorer.exe URL"

This also works to open local folders.

Geoff M
  • 61
  • 1
  • 1
0

You need to call ShellExecute.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

Try this:

Sub OpenURL()
    Dim url As String
    url = "https://www.example.com"
    
    ' Open URL in the default web browser
    ThisWorkbook.FollowHyperlink url
End Sub

Alternate Solution:
------------------

Sub OpenURL()
    Dim url As String
    url = "https://www.example.com"
    
    ' Open URL in the default web browser
    Shell "cmd /c start " & url
End Sub