9

下面的代码有效。但是,如果我注释掉该行Dim objRequest As MSXML2.XMLHTTP并取消注释该行Dim objRequest As Object,它会失败并显示错误消息:

参数不正确

为什么,我能做些什么(如果有的话)?

Public Function GetSessionId(strApiId, strUserName, strPassword) As String

    Dim strPostData As String

    Dim objRequest As MSXML2.XMLHTTP
    'Dim objRequest As Object '

    strPostData = "api_id=" & strApiId & "&user=" & strUserName & "&password=" & strPassword

    Set objRequest = New MSXML2.XMLHTTP
    With objRequest
        .Open "POST", "https://api.clickatell.com/http/auth", False
        .setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
        .send strPostData
        GetSessionId = .responseText
    End With

End Function

科里,是的,我知道我必须这样做才能让我的代码在不引用 MSXML 类型库的情况下工作。这不是这里的问题。Dim objRequest As Object无论我是否使用,使用时代码都会失败

Set objRequest = NEW MSXML2.XMLHTTP与参考,或

Set objRequest = CreateObject("MSXML2.XMLHTTP")没有参考。

4

3 回答 3

19

出于某种原因,这有效:

Dim strPostData As String
Dim objRequest As Object

strPostData = "api_id=" & strApiId & "&user=" & strUserName & "&password=" & strPassword

Set objRequest = New MSXML2.XMLHTTP
With objRequest
  .Open "POST", "https://api.clickatell.com/http/auth", False
  .setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
  .send (strPostData)
   GetSessionId = .responseText
End With

强烈建议使用 URL 编码函数strPostData,而不是通过字符串连接构建URL 编码:

strPostData = "api_id=" & URLEncode(strApiId) & _
              "&user=" & URLEncode(strUserName) & _
              "&password=" & URLEncode(strPassword)

URLEncode()此线程中有几个 VBA 函数的选择:如何在 Excel VBA 中对字符串进行 URL 编码?

于 2008-11-21T14:24:52.743 回答
3

如果您使用 Dim objRequest As Object 那么您需要编码:
Set objRequest = CreateObject("MSXML2.XMLHTTP")

于 2008-11-21T13:54:28.653 回答
0

我意识到这与上面 Tomalek 的代码几乎相同(归功于您!),但是这个问题帮助我找到了解决我遇到的问题的完整解决方案(Excel 提交到 PHP 服务器,然后处理响应)......因此,如果这对其他人有任何帮助:

Sub Button1_Click2()

Dim objXMLSendDoc As Object
Set objXMLSendDoc = New MSXML2.DOMDocument
objXMLSendDoc.async = False
Dim myxml As String
myxml = "<?xml version='1.0'?><Request>Do Something</Request>"
If Not objXMLSendDoc.LoadXML(myxml) Then
    Err.Raise objXMLSendDoc.parseError.ErrorCode, , objXMLSendDoc.parseError.reason
End If

Dim objRequest As MSXML2.XMLHTTP
Set objRequest = New MSXML2.XMLHTTP
With objRequest
    .Open "POST", "http://localhost/SISADraftCalcs/Test2.php", False
    .setRequestHeader "Content-Type", "application/xml;charset=UTF-16"
    .setRequestHeader "Cache-Control", "no-cache"
    .send objXMLSendDoc
End With

Dim objXMLDoc As MSXML2.DOMDocument
Set objXMLDoc = objRequest.responseXML
If objXMLDoc.XML = "" Then
    objXMLDoc.LoadXML objRequest.responseText
    If objXMLDoc.parseError.ErrorCode <> 0 Then
        MsgBox objXMLDoc.parseError.reason
    End If
End If

Dim rootNode As IXMLDOMElement
Set rootNode = objXMLDoc.DocumentElement

MsgBox rootNode.SelectNodes("text").Item(0).text

End Sub
于 2010-02-22T16:26:59.423 回答