excel - 打开链接并在链接中搜索动态关键字的 VBA 代码
问题描述
我一直在对此进行大量研究,但我似乎无法确切弄清楚如何解决我的问题。在 N:N 列中,我有数百个要循环和打开的链接。代码打开它们后,我有另一个工作表,其中包含我希望代码在搜索每个单独的链接时引用的单词/短语的动态列表。如果代码在页面中找不到任何内容,它会关闭窗口并转到下一个链接。如果它确实找到匹配项(不需要区分大小写),那么它会复制相应 O:O 单元格中的所有单词/短语,每个单元格都用“;”分隔。
根据我的研究,我有这段代码可以打开链接:
Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
Dim x As Integer
Dim links As Hyperlinks
Set links = ActiveSheet.Hyperlinks
For x = 1 To links.Count
ie.navigate links.Item(x).Address, Nothing, "_blank"
Next
但是,我似乎找不到任何东西可以帮助我处理这段代码的最后一部分。我对 VBA 相当熟悉,但这超出了我的技能范围。
提前谢谢你!
解决方案
要在网页中搜索关键字或文本,您可以参考下面的代码示例。
Sub scraper()
Dim site As String
Dim lastRow As Long
Dim ie
With ActiveSheet
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
Set ie = CreateObject("internetexplorer.application")
ie.Visible = True
ie.navigate site
'idle while ie is busy
Do
Loop Until ie.readystate = 3
Do
Loop Until ie.readystate = 4
With ie.document
.getelementbyid("UserName").Value = uName
.getelementbyid("Password").Value = uPass
.forms(0).submit
End With
On Error GoTo error
Do
Loop Until ie.readystate = 3
Do
Loop Until ie.readystate = 4
For i = 2 To lastRow
site = Range("A" & i).Value
ie.navigate site
Do
Loop Until ie.readystate = 3
Do
Loop Until ie.readystate = 4
msg = ie.document.Body.innerhtml
If InStr(msg, "Text To Find") = 0 Then
ActiveSheet.Range("B" & i).Value = "Not Found"
Else
ActiveSheet.Range("B" & i).Value = "Found"
End If
jump:
Next i
Exit Sub
error:
ActiveSheet.Range("B" & i).Value = "Unknown Error!"
Resume jump
End Sub
这是示例代码,您可以尝试根据自己的要求对其进行修改。
参考:
对于将值从一个单元格复制粘贴到另一个单元格,您可以参考下面的链接可能会给您一个想法。
推荐阅读
- pentaho - 如何在 Pentaho 仪表板上插入有条件的图像?
- visual-studio - VS 2017 在调试期间显示不正确的 C++ Unicode 文字
- python - 一段时间后python dymola连接失败
- python - 如何使用 Boto3 将多个参数传递给 AWS SSM send_command
- d3.js - 如何更改此折线图中每个部分的颜色?
- sql - 如何获取表中最新日期和 Oracle SQL 中以前日期值的值差异?
- reactjs - React 路由器中断 index.html 脚本
- python - 使用用户输入的纬度和经度在底图上绘制网格
- javascript - bootstrap 一次只打开一个
- python - 根据某些列条件从熊猫数据框中获取所有行组合?