无法在由函数填充的子过程中打印所有结果

问题描述 投票:1回答:1

我在vba中编写了一个脚本来打印PrintResult()函数填充的子程序getPOST()中的所有结果。我当前的尝试是仅打印已解析内容的最后结果。我知道可以将结果存储在字典中,以便一次打印所有这些,但无法理解该特定用法。

保持现有设计的完整性非常重要。

目前的尝试:

Function getPOST() As String
    Const link$ = "https://admintool.noah-connect.com/widget/attendees"
    Dim Http As New XMLHTTP60, Html As New HTMLDocument
    Dim elem As Object, tRow As Object, oName As Object, oCom As Object

    With Http
        .Open "GET", link, False
        .send
        Html.body.innerHTML = .responseText
        For Each elem In Html.getElementsByTagName("tbody")(0).getElementsByTagName("tr")
            Set oName = elem.getElementsByTagName("td")(0)
            Set oCom = elem.getElementsByTagName("td")(1)
            getPOST = oName.innerText & "-" & oCom.innerText
        Next elem
    End With
End Function

Sub PrintResult()
    Debug.Print getPOST()
End Sub

如何在由PrintResult()函数填充的getPOST()中打印所有结果?

excel vba function web-scraping
1个回答
1
投票

不确定你的意思是保留设计所以给出字符串返回和dict(作为对象)返回方法

Option Explicit
Public Sub PrintResult()
    Dim dict As Object, key As Variant
    Set dict = getPOST
    For Each key In dict.keys
        Debug.Print dict(key)
    Next
End Sub

Public Function getPOST() As Object
    Const link$ = "https://admintool.noah-connect.com/widget/attendees"
    Dim http As New XMLHTTP60, html As New HTMLDocument
    Dim elem As Object, tRow As Object, oName As Object, oCom As Object
    Dim i As Long, dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
    With http
        .Open "GET", link, False
        .send
        html.body.innerHTML = .responseText
        For Each elem In html.getElementsByTagName("tbody")(0).getElementsByTagName("tr")
            i = i + 1
            Set oName = elem.getElementsByTagName("td")(0)
            Set oCom = elem.getElementsByTagName("td")(1)
            dict(i) = oName.innerText & "-" & oCom.innerText
        Next elem
    End With
    Set getPOST = dict
End Function

Option Explicit
Public Sub PrintResult()
    Dim items() As String, result As String, i As Long
    result = getPOST
    items = Split(result, "###")
    For i = LBound(items) To UBound(items)
        Debug.Print items(i)
    Next
End Sub
Public Function getPOST() As String
    Const link$ = "https://admintool.noah-connect.com/widget/attendees"
    Dim http As New XMLHTTP60, html As New HTMLDocument
    Dim elem As Object, tRow As Object, oName As Object, oCom As Object, result As String
    result = ""
    With http
        .Open "GET", link, False
        .send
        html.body.innerHTML = .responseText
        For Each elem In html.getElementsByTagName("tbody")(0).getElementsByTagName("tr")
            Set oName = elem.getElementsByTagName("td")(0)
            Set oCom = elem.getElementsByTagName("td")(1)
            result = result & oName.innerText & "-" & oCom.innerText & "###"
        Next elem
    End With
    getPOST = result
End Function
© www.soinside.com 2019 - 2024. All rights reserved.