简体   繁体   English

如何优化 excel VBA 点击 url

[英]How to optimize excel VBA for clicking url

Run time error "70" while VBA is running. VBA 正在运行时出现运行时错误“70”。

Sometime the code runs smooth but sometime does not.有时代码运行流畅,但有时不流畅。 Wondering if there is more reliable code for proceeding.想知道是否有更可靠的代码可以继续进行。 It always stop in If link.innerHTML = "Balance Sheet" Then end if它总是停在If link.innerHTML = "Balance Sheet" Then end if

Public Sub Get()

Dim ie As Object
Dim URL As String, link As Object, alllinks As Object
Dim eRowa As Long, eRowb As Long, eRowc As Long
Dim var As Object

Set var = ThisWorkbook.Worksheets("Sheet2").Cells(1, 1)
URL = "https://www.marketwatch.com/investing/stock/" & var & "/financials"

Set ie = CreateObject("internetexplorer.application")

With ie

    .Visible = True
    .navigate URL

    While .Busy Or .readyState < 4: DoEvents: Wend

    Set alllinks = ie.document.getElementsByTagName("a")

    For Each link In alllinks

         If link.innerHTML = "Balance Sheet" Then

             link.Click

         End If

    Next link

    While .Busy Or .readyState < 4: DoEvents: Wend

End With

Set ie = Nothing


End Sub

Expect smooth running without error 70期望顺利运行,没有错误 70

Use a timed loop to wait for presence of a tag.使用定时循环等待标签的a Use an attribute = value css selector with $ ends with operator for faster targeting of the appropriate element使用属性 = 值 css 选择器和 $ 以运算符结尾,以更快地定位适当的元素

Option Explicit

Public Sub GetInfo()
    Dim ie As Object, url As String, link As Object
    Dim var As Range, t As Date
    Const MAX_WAIT_SEC As Long = 10

    Set var = ThisWorkbook.Worksheets("Sheet2").Cells(1, 1)

    url = "https://www.marketwatch.com/investing/stock/" & var.value & "/financials"

    Set ie = CreateObject("InternetExplorer.Application")

    With ie
        .Visible = True
        .navigate2 url

        While .Busy Or .readyState < 4: DoEvents: Wend

        t = Timer
        Do
            On Error Resume Next
            Set link = .document.querySelector("[href$='/balance-sheet']")
            On Error GoTo 0
            If Timer - t > MAX_WAIT_SEC Then Exit Do
        Loop While link Is Nothing

        If link Is Nothing Then Exit Sub

        link.Click

        While .Busy Or .readyState < 4: DoEvents: Wend

        Stop '<== Delete me later
        .Quit
    End With
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM