VBA打开网页的4种方法,每一种方法都不能错过

VBA打开网页的4种方法,每一种方法都不能错过

技术教程gslnedu2025-04-03 20:42:556A+A-

VBA代码提供了一些访问网页的途径,如果不了解一下,似乎真不知道如何入手。

本节将学会,如何通过VBA代码访问互联网网页。

如下图所示,分别有4种方法,掌握其中一种,就可以了。

首先在VBE编辑器里新建一个窗体,然后新建4个按钮,然后分别对按钮的Click事件进行编程。

通过按钮的单击事件来访问网页,整个流程就是这么简单。

下面用代码来实现上面的流程。

每个按钮其实分别调用了一个过程,过程写到了模块里,也可以写到窗体代码里,没有区别。

Private Sub CommandButton1_Click()
OpenWebApi
End Sub

Private Sub CommandButton2_Click()
OpenWebHyperlink
End Sub

Private Sub CommandButton3_Click()
OpenWebExplorer
End Sub

Private Sub CommandButton4_Click()
OpenWebShell
End Sub

上面的代码就是按钮单击事件代码,每个代码的过程不同,过程执行后直接打开相应网页。

四种方法分别是:

  1. 通过API函数打开网页。
  2. 用FollowHyperLink方法打开网页
  3. 用InternetExplorer对象
  4. 用Shell语句打开网页

然后新建一个模块,把下面的代码放进去。

Public Const webPath = "https://www.toutiao.com/c/user/50527634494/#mid=1554566493712386"
'用API打开默认的浏览器
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
Sub OpenWebApi()
  ShellExecute 0&, vbNullString, webPath, vbNullString, vbNullString, vbNormalFocus
End Sub

'用“FollowHyperlink”方法
Sub OpenWebHyperlink()
  ActiveWorkbook.FollowHyperlink Address:=webPath, NewWindow:=True
End Sub

'用“InternetExplorer”对象
Sub OpenWebExplorer()
  Dim IE As Object
  Set IE = CreateObject("InternetExplorer.Application")
  IE.Visible = True
  IE.Navigate (webPath)
End Sub
'用Shell语句
Sub OpenWebShell()
  Dim url As String
  url = webPath
  Shell "C:\Program Files\Internet Explorer\IEXPLORE.EXE " & url, vbNormalFocus
End Sub

重点说一下,WebPath变量就是想要访问的网页地址,使用的时候更换WebPath变量值即可以。

本示例把WebPath变量设置成一个常量了,结果是一样的。

多掌握一点知识,不会没有好处,留意当下的一些小细节,总有一天,会感觉到,曾经的努力并不是白费功夫。

欢迎关注、收藏

---END---

点击这里复制本文地址 以上内容由朽木教程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

朽木教程网 © All Rights Reserved.  蜀ICP备2024111239号-8