且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 VBA 在默认浏览器中打开一个 html 页面?

更新时间:2023-09-01 15:36:52

您可以使用 Windows API 函数 ShellExecute 来做到这一点:

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

如评论中所述,要使其在 64 位下工作,您需要在 Private Declare Line 中添加 PtrSafe,如下所示:

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 _

关于安全性的简短说明:如果 URL 来自用户输入,请确保严格验证输入,因为 ShellExecute 将执行具有用户权限的任何命令,也是 格式 c:如果用户是管理员,则会执行.

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.