2016-06-17 63 views
0

我對於VBA和VBA在Excel中相當新,我一直在試圖找出如何根據一個單元格值(「Guid」)有條件地抓取Web數據並沒有真正找到一種方法來推動這一功能 - 使其具有動態性。到目前爲止,我只能得到它來檢索一個特定單元格的數據,並在另一個指定的單元格中打印。我相信我只是缺少某種循環變量函數? (除此之外可能有更正確的編寫代碼的方式)。在變量url(網址擴展名)的Excel中進行網絡抓取

Sub ie_open() 
    Dim wb As Workbook 
    Dim ws As Worksheet 
    Dim TxtRng As Range 
    Dim Guid As Range 
    Dim ie As Object 
    Dim URL As String 

    URL = "https://url.com/userpage=" 
    Set wb = ActiveWorkbook 
    Set ws = wb.Sheets("Detail Report - Individuals") 
    Set Guid = ws.Range("E2") 
    Set TxtRng = ws.Range("F2") 
    Set ie = CreateObject("INTERNETEXPLORER.APPLICATION") 

    ie.NAVIGATE (URL + Guid) 
    ie.Visible = True 

    While ie.ReadyState <> 4 
    DoEvents 
    Wend 

    TxtRng = ie.document.getelementbyid("lbl_Location").innertext 

End Sub 

在此先感謝您。

回答

0

打開對HTML元素的引用(轉到工具 - 引用。您還應該打開對Microsoft Internet控件的引用,以便您可以將IE聲明爲InternetExplorer對象而不僅僅是一個對象,但這不是必需的) ,那麼你可以通過像每個元素循環

Sub ie_open() 
Dim wb As Workbook 
Dim ws As Worksheet 
Dim TxtRng As Range 
Dim Guid As Range 
Dim ie As Object 
Dim URL As String 
'ADDED THIS 
Dim sl as Ihtmlelement 
Dim r as long = 1 

URL = "https://url.com/userpage=" 
Set wb = ActiveWorkbook 
Set ws = wb.Sheets("Detail Report - Individuals") 
Set Guid = ws.Range("E2") 
Set TxtRng = ws.Range("F2") 
Set ie = CreateObject("INTERNETEXPLORER.APPLICATION") 

ie.NAVIGATE (URL + Guid) 
ie.Visible = True 

While ie.ReadyState <> 4 
DoEvents 
Wend 

For each sl in ie.document.all 
    ws.cells(r, 1).value = sl.innertext 
    r = r + 1 
Next 

'TxtRng = ie.document.getelementbyid("lbl_Location").innertext 

End Sub 

編輯:忘了遞增循環的r變量,我覺得應該是IE.Document.All,而不是僅僅IE.Document初始化循環