B 列包含 URL
C 列旨在输出是否有效,或者是否是重定向
D 列,如果是重定向,就是重定向到的 URL
以下宏运行良好,但偶尔会出现误报。我找到了一些例子:https://www.samsung.com/us/support/troubleshooting/TSG01003149/ https://www.samsung.com/us/support/answer/ANS00080450/ https://www.samsung.com/us/support/troubleshooting/TSG01108764/
我希望这些是重定向,但由于某种原因宏输出 200。为什么?
这是宏:
Sub CheckURLValidity()
Dim ws As Worksheet
Dim lastRow As Long
Dim url As String
Dim httpRequest As Object
Dim responseCode As Long
Set ws = ActiveSheet
' Find the last row with data in column A
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
' Create an HTTP request object
Set httpRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
httpRequest.Option(WinHttpRequestOption_EnableRedirects) = False
For i = 2 To lastRow
url = ws.Cells(i, 2).Value
' Check if the URL is empty
If Len(url) > 0 Then
httpRequest.Open "GET", url, False
httpRequest.Send
responseCode = httpRequest.Status
' Check the response code
Select Case responseCode
Case 200
ws.Cells(i, 3).Value = "200 Valid"
Case 404
ws.Cells(i, 3).Value = "404 Not Found"
Case 301
ws.Cells(i, 3).Value = "301 Moved Permanently"
ws.Cells(i, 4).Value = httpRequest.getResponseHeader("Location")
Case 302
ws.Cells(i, 3).Value = "302 Found"
ws.Cells(i, 4).Value = httpRequest.getResponseHeader("Location")
Case 307
ws.Cells(i, 3).Value = "307 Temporary Redirect"
ws.Cells(i, 4).Value = httpRequest.getResponseHeader("Location")
Case 308
ws.Cells(i, 3).Value = "308 Permanent Redirect"
ws.Cells(i, 4).Value = httpRequest.getResponseHeader("Location")
Case Else
ws.Cells(i, 3).Value = responseCode & " - Other"
ws.Cells(i, 4).Value = httpRequest.getResponseHeader("Location")
End Select
End If
Next i
Set httpRequest = Nothing
End Sub
我在这一行中尝试了 true 和 false,似乎没有什么区别:
httpRequest.Option(WinHttpRequestOption_EnableRedirects) = False
我做错了什么和/或如何更新宏以正确检测这些重定向?
您使用的是后期绑定,因此 Excel VBA 不知道
WinHttpRequestOption_EnableRedirects
代表什么:它被视为未声明的变量并分配了默认值零。
添加
Const WinHttpRequestOption_EnableRedirects = 6
到右上方
Sub CheckURLValidity()
另外 - 在每个模块的顶部使用
Option Explicit
,以便为您标记。