你可以通过在sub中创建xhr对象并传递给函数来提高效率,然后只看响应头link来区分
Option Explicit
Public Sub Test()
Dim urls(), i As Long, xhr As Object
Set xhr = CreateObject("MSXML2.XMLHTTP")
urls = Array("https://fast.wistia.net/embed/iframe/vud7ff4i6wyh", "https://fast.wistia.net/embed/iframe/vud7ff4i6w")
For i = LBound(urls) To UBound(urls)
MsgBox CheckValidURL(urls(i), xhr)
Next
End Sub
Public Function CheckValidURL(ByVal url As String, ByVal xhr As Object) As Boolean
With xhr
.Open "GET", url, False
.send
CheckValidURL = Not .getResponseHeader("link") = vbNullString
End With
End Function
替代方案:
在函数测试中是否存在仅在有效链接中的 id 或字符串(以您的方式)
Public Sub Test()
Dim urls(), i As Long, html As HTMLDocument, xhr As Object
Set xhr = CreateObject("MSXML2.XMLHTTP"): Set html = New HTMLDocument
urls = Array("https://fast.wistia.net/embed/iframe/vud7ff4i6wyh", "https://fast.wistia.net/embed/iframe/vud7ff4i6w")
For i = LBound(urls) To UBound(urls)
MsgBox CheckValidURL(urls(i), xhr, html)
Next
End Sub
Public Function CheckValidURL(ByVal sURL As String, ByVal xhr As Object, ByVal html As HTMLDocument) As Boolean
With xhr
.Open "GET", sURL, False
.send
html.body.innerHTML = .responseText
End With
CheckValidURL = html.querySelectorAll("#wistia_video").Length > 0
End Function
使用 Instr 也可以
Option Explicit
Public Sub Test()
Dim urls(), i As Long, html As HTMLDocument, xhr As Object
Set xhr = CreateObject("MSXML2.XMLHTTP")
urls = Array("https://fast.wistia.net/embed/iframe/vud7ff4i6wyh", "https://fast.wistia.net/embed/iframe/vud7ff4i6w")
For i = LBound(urls) To UBound(urls)
MsgBox CheckValidURL(urls(i), xhr)
Next
End Sub
Public Function CheckValidURL(ByVal sURL As String, ByVal xhr As Object) As Boolean
With xhr
.Open "GET", sURL, False
.send
CheckValidURL = InStr(.responseText, "html") > 0
End With
End Function
重写你的:
Option Explicit
Public Sub Test()
Dim urls(), i As Long, html As HTMLDocument, xhr As Object
Set xhr = CreateObject("MSXML2.XMLHTTP")
urls = Array("https://fast.wistia.net/embed/iframe/vud7ff4i6wyh", "https://fast.wistia.net/embed/iframe/vud7ff4i6w")
For i = LBound(urls) To UBound(urls)
MsgBox CheckValidURL(urls(i), xhr)
Next
End Sub
Public Function CheckValidURL(ByVal sURL As String, ByVal xhr As Object) As Boolean
With xhr
.Open "GET", sURL, False
.send
CheckValidURL = UBound(Split(.responseText, "<script", , vbTextCompare)) > 0
End With
End Function