【问题标题】:Pass HTMLDocument from Sub to Function将 HTMLDocument 从 Sub 传递给 Function
【发布时间】:2021-02-06 06:39:39
【问题描述】:

我正在尝试将在 Sub 中使用的 HMTL 文档引用到函数;我不断收到以下错误:

运行时错误“424”:

需要对象

我对 VBA 很陌生,我知道我做错了什么,但我就是不知道是什么。这是我的代码:

Dim ie As InternetExplorer

Function findAssetNumber(name1 As String, name2 As String, HTMLDoc As HTMLDocument)
    
    With HTMLDoc
        
        If Not .getElementsByName(name1)(0) Is Nothing Then
            .getElementsByName(name1)(0).Value = mainSheet.Range("E19").Value
            .getElementsByClassName("panelButton")(2).Click
            .getElementsByClassName("rightAlign")(1).getElementsByTagName("a")(0).Click
        Else
            .getElementsByName("name2")(0).Value = mainSheet.Range("E19").Value
            .getElementsByClassName("panelButton")(2).Click
            .getElementsByClassName("rightAlign")(0).getElementsByTagName("a")(0).Click
        End If
            
    End With
        
End Function

Sub Ticket()
    Dim HTMLDoc As HTMLDocument
    Dim locationOptions As IHTMLElementCollection
    Dim terminalCount As Integer
    Dim termNumberShort As String
    Dim termNumberLong As String
        
    Set mainSheet = ThisWorkbook.Worksheets("HHACRMA")
    Set locationSheet = ThisWorkbook.Worksheets("Location")
    Set ie = New InternetExplorer
        
    'Get terminal numbers
        
    termNumberLong = mainSheet.Range("B3").Value
    ActiveSheet.Range("A40") = termNumberLong
    termNumberShort = Left(Range("A40").Value, 3)
        
    'Navigate to ticket system
    With ie
        .Visible = 1
        .navigate "link"
    
        Do While .Busy Or .ReadyState <> 4
            DoEvents
        Loop
    
        Set HTMLDoc = ie.document
        
    End With
        
    'Adding the note/assets
        
    With HTMLDoc
         
        findAssetNumber "7.25.0.0.0.0.2.9.0.0.1.2.3.1.5.3.3.0.1.3.1.5.0.0.1.2.9.3.1.9.2.1.3.1.0.1.1.1.30.1.30.1.4.1", _
                        "7.25.0.0.0.0.2.7.0.0.1.4.3.1.5.3.3.0.1.3.1.5.0.0.1.2.9.3.1.9.2.1.3.1.0.1.1.1.30.1.30.1.4.1", _
                        HTMLDoc
    End With
End Sub

我正在尝试将 Internet Explorer 对象从 Sub 传递给 Function 以使我的代码看起来更清晰。我试图在我的 Sub 中避免多个 If/Else 语句,所以我认为创建一个自动处理 if/else 的函数会更容易和更清晰。错误指向这一行:

.getElementsByName("name2")(0).Value = mainSheet.Range("E19").Value

【问题讨论】:

  • 我预计会出现编译错误,因为函数签名中没有 ByVal MainSheet As Worksheet。请同时包含相关的 html。
  • 我可以看到您已经在全局范围内声明了 IE 对象。您是否直接尝试在函数中使用 ie.document 而不是将 HTML 文档作为参数传递?如果没有,您可以使用它进行测试。它可以帮助您访问文档。另外,尝试检查mainSheet 对象是否可用。让我们知道您的测试结果。

标签: html vba object internet-explorer parameter-passing


【解决方案1】:

在函数 arglist 内的 HTMLDoc 之前添加 ByVal

Function findAssetNumber(name1 As String, name2 As String, ByVal HTMLDoc As HTMLDocument)

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多