我一直在尝试编写excel VBA代码,点击放在HTML表格中的图像。我想点击的图片只有源代码。
我尝试用4种不同的方式点击图片,但这些都没有效果。谁能帮助我如何编写VBA代码?
1
Dim HTMLDoc As Object
Set HTMLDoc = IE.document
Dim ElementCol As Object
Set ElementCol = HTMLDoc.getElementsByTagName("td")
For Each link In ElementCol
If link.innerHTML = "excel.jpg" Then
link.Click
Exit For
End If
Next link
2
Dim HTMLDoc As Object
Set HTMLDoc = IE.document
Dim i As Object
For Each i In HTMLDoc.images
If i.src = "../images/excel.jpg" Then
i.Click
Exit for
End If
Next i
3
Dim HTMLDoc As Object
Set HTMLDoc = IE.document
Dim img As Object
For Each img In HTMLDoc.all
If img.innerHTML = "excel.jpg" Then
img.Click
Exit For
End If
Next img
4
Dim HTMLDoc As Object
Set HTMLDoc = site.document
Dim tdCollection As Object
Set tdCollection = HTMLDoc.all
For Each cell In tdCollection
If cell.ID = "singleXLS" Then
cell.Click
Exit Sub
End If
Next
这是HTML代码。
<tbody><tr>
<td id="singleXLS" onclick="javascript:gCognosViewer.getRV().viewReport('spreadsheetML');" return="" true;"="" style="cursor:hand;" valign="middle" align="center">
<img src="../images/excel.jpg" border="0"></td>
<td> </td>
正如所建议的,这是我正在使用的代码。
Sub click_img()
Dim URL As String
Dim HTMLDoc As Object
Set site = CreateObject("internetexplorer.application")
URL = Range("B2").Value 'There is an URL in cell B2
site.navigate URL
site.Visible = True
While site.busy
Wend
Do Until site.readyState = 4
DoEvents
Loop
Set HTMLDoc = site.Document
HTMLDoc.getElementById("singleXLS").getElementsByTagName("img")(0).Click 'Error is here
End Sub
答案 0 :(得分:0)
而不是:
Set HTMLDoc = site.Document
HTMLDoc.getElementById("singleXLS").getElementsByTagName("img")(0).Click
尝试:
Dim s, i
Set HTMLDoc = site.Document
Set s = HTMLDoc.getElementById("singleXLS")
If Not s Is Nothing Then
Set i = s.getElementsByTagName("img")(0)
If Not i Is Nothing Then
i.Click
Else
Debug.Print "Img not found!"
End If
Else
Debug.Print "singleXLX not found!"
End If
更多代码,但它可以帮助您确定准确的问题