Search code examples
vbabrowsernavigation

Open an html page in default browser with VBA?


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.


Solution

  • 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.