2012-07-11 84 views
2

嘗試通過Excel接收網站源代碼VBA適用於大約4000個字,40000個字符。然後停止。我不知道爲什麼。Excel VBA無法讀取超過40,000個字符的網頁源

任何人都可以幫助我嗎?

Option Explicit 
Private Const INTERNET_FLAG_NO_CACHE_WRITE = &H4000000 
Private Declare Function InternetOpen Lib "Wininet.dll" Alias "InternetOpenA" (ByVal lpszAgent As String, ByVal dwAccessType As Long, ByVal lpszProxyName As String, ByVal lpszProxyBypass As String, ByVal dwFlags As Long) As Long 
Private Declare Function InternetReadFile Lib "Wininet.dll" (ByVal hFile As Long, ByVal sBuffer As String, ByVal lNumBytesToRead As Long, lNumberOfBytesRead As Long) As Integer 
Private Declare Function InternetOpenUrl Lib "Wininet.dll" Alias "InternetOpenUrlA" (ByVal hInternetSession As Long, ByVal sUrl As String, ByVal sHeaders As String, ByVal lHeadersLength As Long, ByVal lFlags As Long, ByVal lContext As Long) As Long 
Private Declare Function InternetCloseHandle Lib "Wininet.dll" (ByVal hInet As Long) As Integer 

Public Sub GetWebPageData() 

    Dim hInternet, hSession, lngDataReturned As Long 
    Dim iReadFileResult As Integer 
    Dim sBuffer As String * 64 
    Dim sTotalData As String 
    Dim sUrl As String 
    Dim sLine As String 

    sUrl = "http://www.engadget.com/" 'Long Website here 
    hSession = InternetOpen("", 0, vbNullString, vbNullString, 0) 

    If hSession Then hInternet = InternetOpenUrl(hSession, sUrl, vbNullString, 0, INTERNET_FLAG_NO_CACHE_WRITE, 0) 

    If hInternet Then 
    iReadFileResult = InternetReadFile(hInternet, sBuffer, 128, lngDataReturned) 

    sTotalData = sBuffer 

    Do While lngDataReturned <> 0 
     iReadFileResult = InternetReadFile(hInternet, sBuffer, 128, lngDataReturned) 
     sTotalData = sTotalData + Mid(sBuffer, 1, lngDataReturned) 
    Loop 
    End If 

    iReadFileResult = InternetCloseHandle(hInternet) 

    'WEBPAGE loaded into sTotalData 
    Cells(2, 2) = sTotalData 
End Sub 
+0

我好奇,爲什麼你使用這種方法,我使用標準的XMLHTTP請求查詢同一頁面,速度更快,最終字符串的數據量是原來的兩倍,這些代碼返回的數據在我的機器上沒有意義,tho呃,我使用64位,如果這有什麼區別。 – SWa 2012-07-11 13:07:40

+0

你能告訴我任何代碼嗎?我剛剛發現了兩種方法(1.在VBA中打開IExplorer,等待並關閉,非常慢,2.我的方法)。我很感謝任何幫助加快我的計劃;-) – 2012-07-17 09:25:19

回答

0

的問題是該行

Cells(2, 2) = sTotalData 

返回一個字符串轉換爲電池limnited 32767個字符在Excel 2007/2010,即使sTotalData長於。

參考this link

+0

沒有時間來證明它,但聽起來非常好。感謝你,非常感謝! – 2012-07-17 09:21:31

0

按照要求,得到了完整的源代碼的另一種方式:

Function GetSource(url As String) As String 

With CreateObject("MSXML2.XMLHTTP") 
    .Open "GET", url 
    .Send 
    Do: DoEvents: Loop Until .Readystate = 4 
    GetSource = .responsetext 
    .abort 
End With 

End Function 
+0

嘿,我正在尋找一個解決方案來接收超過一週的vba的html源代碼。發現速度不夠快。而你的代碼就像:簡單,容易,只有10行代碼,簡單...非常感謝!希望,尋找的人會找到答案! – 2012-07-18 07:59:12

0

你嘗試過:

For i = 1 To Len(sTotalData) Step (Len(sTotalData)/200) '*Line1 of 3 to replace Cells(2, 2) = sTotalData 


Cells(i \ (Len(sTotalData)/200) + 1, "A").Value = "'" & Mid(sTotalData, i, (Len(sTotalData)/200)) '*Line2 of 3 to replace Cells(2, 2) = sTotalData 


Next i '*Line3 of 3 to replace Cells(2, 2) = sTotalData 
相關問題