2012-05-14 20 views
3

我正在使用WinHTTP在Excel VBA宏中執行GET請求。但是,如果我嘗試使用代理服務器在網絡中執行請求,則不起作用。如果我手動配置它,它可以工作,但我不認爲使用我正在開發的工具的人會知道他們的代理服務器。使用WinHTTP和Excel配置代理

有沒有辦法自動配置代理服務器,或從Windows獲取代理配置?這裏有個示例代碼:

Dim result As String 
Dim URL As String 
Dim winHttpReq As Object 
Set winHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1") 

URL = "http://google.com/" 
winHttpReq.Open "GET", URL, False 
winHttpReq.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" 
winHttpReq.setProxy 2, "proxyserver:8080", "" 
winHttpReq.send 
result = winHttpReq.responseText 

在這種情況下,我不想強​​迫用戶找到「訪問代理服務器:8080」地址 - 我要的是一種自動填補。

非常感謝。

回答

1

我從下面的鏈接中獲得了下面的vbScript。您可以使用來獲取代理服務器,並把它作爲一個變量的代碼爲「訪問代理服務器:8080」:

http://www.activexperts.com/activmonitor/windowsmanagement/scripts/networking/client/retrieving/

如果你知道的VBScript - 這是非常相似,VBA,我覺得這應該有很大的幫助。如果你需要幫助寫在VBA中,請告訴我。

On Error Resume Next 

strComputer = "." 
Set objWMIService = GetObject("winmgmts:" _ 
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 

Set colItems = objWMIService.ExecQuery("Select * from Win32_Proxy") 

For Each objItem in colItems 
    Wscript.Echo "Proxy Port Number: " & objItem.ProxyPortNumber 
    Wscript.Echo "Proxy Server: " & objItem.ProxyServer 
    Wscript.Echo "Server Name: " & objItem.ServerName 
    Wscript.Echo 
Next 
+0

嗨!這似乎是這樣的,但每當我嘗試執行查詢時,都會說Win32_Proxy是一個無效的類。我已經嘗試了在MSDN上找到的其他類,並且他們工作,所以我認爲這是該類的特定問題。 –

+0

有趣。這對我有效。如果您發現問題,請告訴我。如果有任何幫助,我在XP上。 –

+0

Win32_Proxy不再可用post win-xp – anand

2

在此頁面中尋找一個答案,同樣的問題在萬一別人絆倒,我想指出this answer,使用VBA-Web項目來解決這個確切的問題,其中提到。然後

您的代碼將是這個樣子:

Dim client As New WebClient 
With client 
    .BaseUrl = "https://www.google.com" 
    .EnableAutoProxy = True 
End With 

Dim request As New WebRequest 
With request 
    .Method = WebMethod.HttpGet 
    .AddHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" 
    .Format = WebFormat.PlainText 
End With 

Dim response As WebResponse 
Set response = client.Execute(request) 
+0

確實非常優雅的解決方案 –