如何从类实例中获取数据

时间:2017-01-30 07:08:17

标签: vba

我是vba中的类编程新手。

这是我第一次尝试使用教学 :Asynchronous HTTP POST Request in MS Access

我正在使用单词vba。

这是我的CXMLHTTPHandler.cls

VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "CXMLHTTPHandler"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit
Dim m_xmlHttp As MSXML2.XMLHTTP

Public Sub Initialize(ByRef xmlHttpRequest As MSXML2.XMLHTTP)
   Set m_xmlHttp = xmlHttpRequest
End Sub

Sub OnReadyStateChange()
Attribute OnReadyStateChange.VB_UserMemId = 0
   Debug.Print m_xmlHttp.readyState
   If m_xmlHttp.readyState = 4 Then
      If m_xmlHttp.Status = 200 Then
         msgbox m_xmlHttp.responseText
      Else
         msgbox "Something Went Wrong"
     End If
   End If
End Sub

这是我的标准模块

Option Explicit
Public xmlHttpRequest As MSXML2.XMLHTTP
Function sasynchreq(url As String)
On Error GoTo FailedState
If Not xmlHttpRequest Is Nothing Then Set xmlHttpRequest = Nothing
Dim MyXmlHttpHandler As CXMLHTTPHandler
Set xmlHttpRequest = New MSXML2.XMLHTTP
'Create an instance of the wrapper class.
Set MyXmlHttpHandler = New CXMLHTTPHandler
MyXmlHttpHandler.Initialize xmlHttpRequest
'Assign the wrapper class object to onreadystatechange.
xmlHttpRequest.OnReadyStateChange = MyXmlHttpHandler
'Get the page stuff asynchronously.
xmlHttpRequest.Open "GET", url, True
xmlHttpRequest.send ""
Exit Function
FailedState:
    msgbox Err.Number & ": " & Err.Description
End Function

Sub test()
    Dim url As String, do_something As String
    url = "http://httpbin.org/html"
    do_something = sasynchreq(url)
    'do somethign with do_something
End Sub

一切正常。如果我想将httprequest分配给某个变量,例如在test sub中,该怎么办?

2 个答案:

答案 0 :(得分:1)

Property语句之后听起来像你一样。在您的情况下,它将是Property Gethttps://msdn.microsoft.com/en-us/library/office/gg264197.aspx)。

在你的课程模块中,输入:

Public Property Get HttpRequest() As MSXML2.XMLHTTP
    Set HttpRequest = m_xmlHttp
End Property

现在,您可以让Module访问类变量,如下所示:

Dim rq as MSXML2.XMLHTTP
set rq = MyXmlHttpHandler.HttpRequest

答案 1 :(得分:0)

我认为您可以期望在退出函数时出现在Send方法上预测的最终有效负载。如果是这样,您的函数签名应如下所示:

Function sasynchreq(url As String) As String

并且在函数体中,应该有:

xmlHttpRequest.send ""
sasynchreq = xmlHttpRequest.responseXML.xml

或类似的东西。然后do_something将立即可用。

长话短说,如果没有同步性问题,那么它的当前编写方式,你的功能并没有回到do_something。无论你返回什么,子测试中的函数签名和局部变量类型应该匹配。如果要返回一个对象,则需要在两个实例中使用Set关键字。