简体   繁体   中英

Excel VBA: Call Sub Procedure from function

My code is retrieving an HTML page as an object, given a certain parameter:

Public Sub MyPage(myparam)
Dim oHtml As HTMLDocument

Set oHtml = New HTMLDocument

With CreateObject("WINHTTP.WinHTTPRequest.5.1")
    .Open "GET", "http://www.example.com" & myparam, False
    .send
    oHtml.body.innerHTML = .responseText
End With

End Sub

I'm defining functions that will use the same object, therefore, I want to minimize the number of connections. So I want to define a function like:

Function myFunction(myparam As String)

Call MyPage(myparam)

'code here

End Function

But this isn't working. When I type =myFunction into a cell, I get the #VALUE! error.

If I just type the code of the sub procedure inside the function, it works, something like:

Function myFunction(myparam As String)

Dim oHtml As HTMLDocument

Set oHtml = New HTMLDocument

With CreateObject("WINHTTP.WinHTTPRequest.5.1")
    .Open "GET", "http://www.example.com" & myparam, False
    .send
    oHtml.body.innerHTML = .responseText
End With

    'code here

End Function

But, as mentioned above, this will require the same connection and object for different functions.

How can I solve this? Thanks

Converting my comment to an answer:

Use your oHtml variable as Public variable .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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