Open an html page in default browser with VBA?
Asked Answered
H

6

51

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.

Harbour answered 2/7, 2010 at 13:49 Comment(0)
N
64

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.

Nazarite answered 2/7, 2010 at 13:55 Comment(8)
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.Harbour
Some may need to add "PtrSafe" in the declare statement: "Private Declare PtrSafe Function ShellExecute..." to make it work in 64bit.Corrida
@ashleedawg: Note that ThisWorkbook only works in ExcelNazarite
@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.Vernievernier
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.Josejosee
ThisWorkbook.FollowHyperlink("http://www.yoursite.com") worked for more.Josejosee
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?Balfour
How to turn this into a function that only executes when a user clicks an excel cell with the troubling url?Antechoir
B
55

You can even say:

FollowHyperlink "www.google.com"

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

ThisWorkbook.FollowHyperlink("http://www.google.com")
Basso answered 14/6, 2012 at 17:2 Comment(10)
If in Excel, you need a workbook object, like ThisWorkbook.FollowHyperlink "www.google.com"Approver
I was receiving Automation Error. So I needed to use http://. Then, the full command is: ThisWorkbook.FollowHyperlink "http://www.google.com.br"Springs
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.Corrida
FollowHyperlink is messing with IE/Edge security, The solution using ShellExecute is more reliable as far as I have experiencedStrep
One problem with FollowHyperlink is that it is trying to interpret the url. If Url returns 404 VBA code fails.Hydrophone
How to close the browser window opened by FollowHyperlink?Borgia
although this solution works.. the accepted solution before this opens the browser with quick response. this solution is slightly slower to open the browser.Triserial
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 has more web-specific options.Vernievernier
ShellExecute can be far faster for https connections as it seems to reuse credentials, whereas FollowHyperlink can trigger reauthorisation processes.Arleyne
Just for information, this works with mailto: syntax to send mail.Fruiterer
S
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:[email protected]",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.

Schutt answered 4/12, 2012 at 17:6 Comment(1)
The URLsi are transformed to lower in access 97.Electromagnetic
K
6

I find the most simple is

shell "explorer.exe URL"

This also works to open local folders.

Kalpak answered 3/8, 2020 at 18:52 Comment(1)
That doesn't open the URL using the default browser.Pulque
A
0

You need to call ShellExecute.

Anticlinorium answered 2/7, 2010 at 13:51 Comment(1)
The link is dead... Just FYIMaura
W
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
Winonawinonah answered 18/5, 2023 at 15:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.