vba - 如何在 excel 2016 中进行图像 url 验证?

标签 vba excel

如果图像 URL 给出 404 错误,有没有办法在 excel 中报告有效或无效?不打开每个图像?例如,检查 404 的 header ?这是我尝试过的一些片段

Function URLExists(url As String) As Boolean
    Dim Request As Object
    Dim ff As Integer
    Dim rc As Variant

    On Error GoTo EndNow
    Set Request = CreateObject("WinHttp.WinHttpRequest.5.1")

    With Request
      .Open "GET", url, False
      .Send
      rc = .StatusText
    End With
    Set Request = Nothing
    If rc = "OK" Then URLExists = True

    Exit Function
EndNow:
End Function
Public Function IsURLGood(url As String) As Boolean
    Dim request As New WinHttpRequest

    On Error GoTo IsURLGoodError
    request.Open "HEAD", url
    request.Send
    If request.Status = 200 Then
        IsURLGood = True
    Else
        IsURLGood = False
    End If
    Exit Function

IsURLGoodError:
    IsURLGood = False
End Function

这些报告所有 URL,对我来说,是的。例如,当我检查时
http://www.bangallawebservices.com/images/BWA22055.jpg

这些肯定会为返回值提供不希望的结果,上图是 404 错误的示例,通过这些代码片段在 excel 中被视为有效 URL。

我还尝试了 Office PowerUp 插件的免费演示,带有 pwrISBROKENURL当某些实际上已损坏时,它返回所有错误(未损坏)。 Excel 被授予通过防火墙对 Internet 的完全访问权限。
https://www.youtube.com/watch?v=HU99-fXNV40

最佳答案

这对我有用。它不返回 bool 值,而是返回实际状态或错误描述(如果在执行期间有一个):

Public Function IsURLGood(url As String)
    Dim request As Object
    Set request = CreateObject("WinHttp.WinHttpRequest.5.1")
    On Error GoTo haveError
    With request
        .Open "HEAD", url
        .Send
        IsURLGood = .Status
    End With
    Exit Function
haveError:
    IsURLGood = Err.Description
End Function

快速测试:

enter image description here

编辑:

您可以执行以下操作,而不是将其作为 UDF 运行:
Sub ProcessUrls()
    Dim c As Range
    For Each c in Activesheet.Range("A1:A20000").Cells
        c.Offset(0, 1).Value = IsURLGood(c.Value) 'put result in ColB
    Next c
End sub

关于vba - 如何在 excel 2016 中进行图像 url 验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44813295/

相关文章:

vba - 使用 ActiveCell.Offset(0, 1).Value 在 VBA 中选择多个单元格

excel - 如何保持所有工作表中的页眉(非静态页眉)相同?

excel - 如何在事件单元格中创建组合框?

python - 创建选择框以基于Excel列中的唯一性传递字符串值

excel - 使用 Power Query 从网站中提取未完全加载的表

Excel - VBA - 创建每个主键的唯一代码组合

vba - 预期错误只能是 440/自动化错误?

c# - Excels 的等效 C# 函数 Norm.S.Inv 函数

c# - 从 Excel 工作表解析日期时间

python - 将网页抓取的表格放入excel(selenium,python)