【发布时间】:2018-05-16 00:48:16
【问题描述】:
我在 vba 中编写了一些代码,以针对某些网站中的某些名称查找某些身份。如果一切都按正确的顺序,代码运行良好,我的意思是如果链接有效,名称与a 标签匹配,最后正则表达式可以找到身份。如果这三个中的任何一个或所有三个都是错误搜索,则脚本将引发错误。我已经在下面的脚本中指定了错误发生的位置。
我希望各位专家为我提供有关如何处理错误并让我的脚本继续运行直到所有链接都用尽的任何解决方案。
由于我对 VBA 了解不多,所以我尝试使用 On error resume next 跳过错误。但是,当我查看结果时,结果却是一团糟。我正在粘贴一个粗略的示例,当我使用 On error resume next 时得到的结果。
Sub Identity_Finder()
Dim http As New XMLHTTP60, html As New HTMLDocument
Dim post As Object, link As Variant, refined_links As String
Dim rxp As New RegExp, identity As Object
For Each link In [{"http://spltech.in/","http://www.unifrostindia.com/","http://www.unitfrostindia.com/","http://www.greenplanet.in/"}]
With http
.Open "GET", link, False
.send '''throws here the first error if the link is invalid
html.body.innerHTML = .responseText
End With
For Each post In html.getElementsByTagName("a")
If InStr(post.innerText, "certain_name") > 0 Then refined_links = post.href: Exit For
Next post
With http
.Open "GET", refined_links, False
.send ''throws another error here if no such link is found
End With
With rxp
.Pattern = "some_regex"
.Global = True
Set identity = .Execute(http.responseText)
End With
r = r + 1: Cells(r, 1) = link
Cells(r, 2) = identity(0) ''''throws another error here if no such identity is noticed
Next link
End Sub
使用On error resume next 我得到了什么:
John executive
Mac lawyer
lulu lawyer
Robin lawyer
Cathy student
预期输出:
John executive
Mac lawyer
lulu
Robin
Cathy student
当我使用On error resume next 时,空字段(未找到时)将被以前的值填充。我怎样才能绕过这个误导性的结果?提前致谢。
【问题讨论】:
-
你有没有把代码一步一步地运行起来,看看逻辑在哪里?如果您通过按
F8开始您的代码,然后再次按以转到代码的下一行等等......这对于调试逻辑问题非常有用:) -
是的,我调试了几次,如果链接不是无效的,我找不到任何问题,名称与
a标签匹配,并且正则表达式找到了我在帖子中已经描述的身份。但是,当这三个中的任何一个与搜索不匹配并且我已经在脚本中标记了发生错误的位置时,我会收到错误消息。谢谢。
标签: vba excel error-handling web-scraping