2016-07-06 251 views
0

我試圖通過使用函數將HTML表格中的單元格提取到Excel單元格中。表是這樣的:插入HTML表格單元格到沒有ID的Excel工作表單元格

    | 1Q | 2Q | 3Q | 
     income | 23 | 34 | 22 | 
     expenses | 11 | 19 | 10 | 
            . 
            . 
            . 

我不能通過ID獲取元素,所以我創建了兩個循環來尋找元素的元素。該代碼可以找到的元素(在我的情況中,「費用」 COL1 2行),但我不知道如何(在這種情況下11)獲取單元格的值向右提前

Dim IE As Object 
Dim doc As Object 
Dim colTR As Object 
Dim colTD As Object 
Dim tr As Object 
Dim td As Object 
Set IE = CreateObject("InternetExplorer.Application") 

IE.Visible = True 
IE.Navigate "www.mywebpage.com" 

Do Until IE.ReadyState = 4 
    DoEvents 
Loop 

Set doc = IE.Document 

Set colTR = doc.GetElementsByTagName("TR") 
For Each tr In colTR 
    Set colTD = tr.GetElementsByTagName("TD") 
    For Each td In colTD 
     If td.innertext = "expenses" Then 
     TheValueIWant = tr.item(1).innertext 
     End If 
    Next td 
Next tr 

IE.Quit 

Set IE = Nothing 
Set doc = Nothing 
Set colTR = Nothing 
Set colTD = Nothing 
Set td = Nothing 
Set tr = Nothing 

感謝

+0

11只是更多的專欄。從您的示例數據中很難說,但可能是1或2或更多。你可以用'debug.print'做一個循環,以便第一次找出它,而不是相應地調整代碼。因此,如果它是第二列,它將是'tr.Cells(2).innertext'。 –

回答

0

斯科特是沒有理由循環所有的tds。

For Each tr In colTR 

    If tr.Cells(0).innerText = "expenses" Then 
     TheValueIWant = tr.Cells(1).innerText 
     MsgBox TheValueIWant 
    End If 

Next 
+0

真棒!它完美的作品 –

+0

高興地協助。先生! – 2016-07-07 04:13:39