使用VBA和Internet Explorer分析HTML

我正在尝试使用VBA代码来单击网站上的“Go”button。 这是源代码。

<div class="actions"> <a id="go" href="javascript:void(null);" title="Go"><img src="/images/button-go-smaller.png"></a> <a id="reset" href="javascript:void(null);" title="Reset All Fields"><img src="/images/button-reset_all.png"></a> </div> 

这是我的VBA代码:

 For Each obj In objCollection If objCollection(i).ID = "go" Then Set objElement = obj Exit For End If Next obj objElement.Click 

但是,在objElement.Click行,我得到一个错误91,这意味着“去”行动无法find。 为什么是这样,我怎样才能访问button?

关于什么…

 Dim objCollection As Object Set objCollection = IE.Document.getElementsbyTagName("a") For Each obj In objCollection If obj.ID = "go" Then obj.Click Exit For End If Next obj 

如果你有一个具有Id的html对象,你可以直接得到这样的东西:

 Dim GoObj As Object Set GoObj = IE.Document.getElementbyId("go") 'Only if it was found you click it If not GoObj is Nothing then GoObj.Click End If 

注意getElementbyId元素和getElementbyId元素之间的区别

这是如何做到这一点的一个很好的例子。

 Dim HTMLDoc As HTMLDocument Dim oBrowser As InternetExplorer Sub Login_2_Website() Dim oHTML_Element As IHTMLElement Dim sURL As String On Error GoTo Err_Clear sURL = "https://www.google.com/accounts/Login" Set oBrowser = New InternetExplorer oBrowser.Silent = True oBrowser.timeout = 60 oBrowser.navigate sURL oBrowser.Visible = True Do ' Wait till the Browser is loaded Loop Until oBrowser.readyState = READYSTATE_COMPLETE Set HTMLDoc = oBrowser.Document HTMLDoc.all.Email.Value = "sample@vbadud.com" HTMLDoc.all.passwd.Value = "*****" For Each oHTML_Element In HTMLDoc.getElementsByTagName("input") If oHTML_Element.Type = "submit" Then oHTML_Element.Click: Exit For Next ' oBrowser.Refresh ' Refresh If Needed Err_Clear: If Err <> 0 Then Debug.Assert Err = 0 Err.Clear Resume Next End If End Sub 

阅读更多: http : //vbadud.blogspot.com/2009/08/how-to-login-to-website-using-vba.html#XwwFWylLQi9rjILC.99