创build一个函数 – Excel VBA

我有一些代码,使得HTTP请求,并在parsing之前从API获取XML。

我的代码的HTTP请求部分总是相同的,唯一改变的参数是我发送请求的URL。 我想知道是否可以将请求转换为函数?

Set xmldoc = CreateObject("Msxml.DOMDocument") Set httpReq = CreateObject("WinHttp.WinHttprequest.5.1") xmldoc.async = False httpReq.Open "GET", myUrl, False httpReq.setRequestHeader "Content-Type", "text/xml" If Sheet2.proxyStatus = "ON" Then httpReq.setProxy 2, Sheet2.proxyServer, "" ElseIf Sheet2.proxyStatus = "OFF" Then httpReq.setProxy 0, "", "" End If httpReq.setTimeouts -1, -1, -1, -1 httpReq.send request xmldoc.LoadXML httpReq.responseText Set xmlElement = xmldoc.DocumentElement 

提出请求后,我使用这样的代码来parsingXML中的数据:

 TotalSessions = xmlElement.SelectSingleNode("//Row[@rowKey='Sessions']/Value[@columnId='SESSIONS']").Text 

parsing信息的代码不能被包含在函数中,因为它正在寻找的节点和它所分配的variables是独特而众多的,但是它需要能够明显地读取由该函数下载的XML。

我已经尝试创build函数,但我不确定什么types来定义它,所以我去了对象:

 Function fetchXML(url As String) As Object Set xmldoc = CreateObject("Msxml.DOMDocument") Set httpReq = CreateObject("WinHttp.WinHttprequest.5.1") xmldoc.async = False httpReq.Open "GET", url, False httpReq.setRequestHeader "Content-Type", "text/xml" If Sheet2.proxyStatus = "ON" Then httpReq.setProxy 2, Sheet2.proxyServer, "" ElseIf Sheet2.proxyStatus = "OFF" Then httpReq.setProxy 0, "", "" End If httpReq.setTimeouts -1, -1, -1, -1 httpReq.send request xmldoc.LoadXML httpReq.responseText Set xmlElement = xmldoc.DocumentElement End Function 

然后我试图调用函数并parsing一些信息:

 fetchXML (coukChannels30DayUrl) coukPPCSessionsSS = xmlElement.SelectSingleNode("//Row[@rowKey='1#11588418521354:1158842490346']/Value[@columnId='SESSIONS']").Text 

但不幸的是,它没有工作,我打电话function错了吗? 这是错误的types? 我甚至可以这样做吗? 大声笑

干杯

好吧,我得到它的工作,我只需要改变这个函数的function:

 Set xmlElement = xmldoc.DocumentElement 

对此:

 Set fetchXML = xmldoc.DocumentElement 

然后在sub中改变这一行:

 fetchXML (coukChannels30DayUrl) 

对此:

 Set xmlElement = fetchXML(coukChannels30DayUrl) 

它的工作非常好,function。