Excel VBA:从函数调用子过程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20149618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 00:35:57  来源:igfitidea点击:

Excel VBA: Call Sub Procedure from function

excelvbaexcel-vba

提问by Nuno Nogueira

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

给定某个参数,我的代码正在将 HTML 页面作为对象检索:

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.

但这不起作用。当我在单元格中键入 =myFunction 时,我得到了 #VALUE!错误。

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

我该如何解决这个问题?谢谢

采纳答案by Kazimierz Jawor

Converting my comment to an answer:

将我的评论转换为答案:

Use your oHtml variableas Public variable.

使用您的oHtml variable作为Public variable.