2017-01-30 3 views
0

vba에서 프로그래밍하는 데 익숙하지 않습니다. 나는 워드 VBA를 사용하고 Asynchronous HTTP POST Request in MS Access클래스 인스턴스에서 데이터를 가져 오는 방법

:

여기 의 가르침을 사용하여 내 첫 번째 시도이다.

은 여기 내 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를 지정하려면 어떻게해야합니까?

답변

1

Property 문 이후입니다. 귀하의 경우에는 Property Get (https://msdn.microsoft.com/en-us/library/office/gg264197.aspx)이됩니다.

클래스 모듈에서

는이를 넣어 :

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

를이 지금과 같이, 클래스 변수로 모듈 액세스를 제공합니다 :

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

도움 주셔서 감사합니다. 나는 하나의 부재중이 콜백을 기다리고 있다고 생각한다. – Rahul

+0

죄송합니다. 질문에 대한 오해를했습니다. 내가 당신의 링크를 읽을 때까지 VBA에서 비동기 작업이 불가능하다고 생각했습니다. 나는 '기다리는'결과와 동등한 결과를 얻는 방법을 모르겠다. 아마도 객체를 얻는 방법과 때를 보여주기 위해 질문을 편집하십시오. 코드의 일부분을'OnReadyStateChange' 루틴에 두는 것조차 수도 있습니다. – Ambie

0

난 당신에 입각 궁극적 인 페이로드를 기대할 수 있다고 생각 함수를 종료 할 때까지 Send 메서드가 있어야합니다. 그래서, 함수의 서명과 같이 보일 것입니다 경우

Function sasynchreq(url As String) As String 

와 함수의 몸을하는이 있어야한다 : 그런

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

또는 무언가를. 그러면 do_something을 즉시 사용할 수 있습니다.

간단히 말해서, 동시성 문제가 없다면 현재 작성된 방식대로 함수가 do_something에 아무것도 반환하지 않습니다. 그것이 무엇이든지 반환하고, 함수 테스트와 하위 테스트 내의 지역 변수 유형이 일치해야합니다. 객체를 반환하는 경우 두 인스턴스 모두에서 Set 키워드를 사용해야합니다.

관련 문제