2017-04-22 64 views
0

此代码有效,但不一致。通常,它失败在这条线:Excel VBA提取Xero报告

For Each objElement In htmlDoc.GetElementsByTagName("td") 

下面是代码:

Dim AppIE 
Dim htmlDoc 
Dim nRow As Integer 
Dim nColNum As Integer 
Dim objElement 
Dim nColCount As Integer 
Set AppIE = CreateObject("InternetExplorer.Application") 
AppIE.Visible = True 'login may be required 
AppIE.Navigate myString 'from clipboard 
While AppIE.Busy 'wait for IE to open 
    DoEvents 
Wend 
While AppIE.ReadyState <> 4 'wait for login 
    DoEvents 
Wend 
While AppIE.Busy 'pause put in by Donald 
    DoEvents 
Wend 
Set htmlDoc = AppIE.Document 
nRow = 0 
nColCount = 0 
nColNum = 0 
For Each objElement In htmlDoc.GetElementsByTagName("td") 
    'If IsNull(objElement.classname) And IsNull(objElement.innertext) Then 
    'Else 
     If objElement.classname = "RowHeader2 MenuLeft" Then 
      nColCount = nColCount + 1 
      Cells(nRow, nColCount).Value = objElement.innertext 
     Else 
      If nColCount >= 1 Then 
       nColNum = nColNum + 1 
       Cells(nRow, nColNum).Value = objElement.innertext 
       If nColNum = nColCount Then 
        nColNum = 0 
        nRow = nRow + 1 
       End If 
       If Len(objElement.classname) = 0 Then 
        nColNum = 0 
        nRow = nRow + 1 
       End If 
      Else 
       nRow = nRow + 1 
       Cells(nRow, 1).Value = objElement.innertext 
      End If 
     End If 
    'End If 
Next 
AppIE.Visible = False 
MsgBox "Done" 
AppIE.Quit 
Set AppIE = Nothing 
+0

当它失败时,它是第一个元素还是其他元素?你得到什么错误代码? –

+0

Hi Rich。当它失败时,它会立即在第一个元素上失败 - 不会产生错误,它必须是它找到零个元素并立即退出For循环。 –

回答

0

此代码似乎让IE来完成导航到Xero的报告...?

'wait for IE to complete the navigaiton to the Xero report ---------------------------------------------------------------------------------------------------------------------------- 
n = 0 
While n = 0 
    For Each objElement In htmlDoc.GetElementsByTagName("td") 
     n = n + 1 
    Next 
    DoEvents 
Wend 
+0

这不是我最强烈的VBA部分,但是我正在寻找,看起来在你尝试获取元素之前,你可以尝试使用一个循环来查找ready和state = 4.所以:当AppIE.Busy或AppIE.ReadyState <> 4:DoEvents:wend –