此vba代码的正确元素ID是什么?

时间:2019-10-23 19:34:02

标签: excel vba internet-explorer automation

我从该站点获得了以下vba代码。该代码将自动在IE中打开网站(将使用不同的url),并且还将导入文件。当我运行这段代码时,由于不正确的elementsTagName以及InputType导致它无法正常工作。什么是正确的代码?我不确定。第二部分是html代码。

请帮助检查代码。

Sub File_Test()
Dim HTMLDoc As MSHTML.HTMLDocument
Dim HTMLButtons As MSHTML.IHTMLElementCollection
Dim HTMLButton As MSHTML.IHTMLElement
Dim btnInput As MSHTML.IHTMLInputElement 
Dim ie As Object 
Dim pointer As Integer 
Set ie = CreateObject("internetexplorer.application") 
ie.Visible = True 
ie.navigate "http://www.htmlquick.com/reference/tags/input-file.html" 
Do While ie.readyState <> READYSTATE_COMPLETE 
Loop 
Set HTMLDoc = ie.document 
Set HTMLButtons = HTMLDoc.getElementsByTagName("Upload Files") 
For Each HTMLButton In HTMLButtons 
    For Each btnInput In HTMLButtons 
        If btnInput.Type = "button" Then 
             HTMLButton.Click btnInput.Value = "C:\temp\test.txt" 
             pointer = 1 
             Exit For 
        End If 
     Next 
     btnInput 
     If pointer = 1 Then Exit For 
  Next 
End sub


    <button title="Upload Files" class="button button--white xc-action-nav__button ng-binding ng-scope" type="button" loading-key="0" ng-click="setLoading('group1', '0'); " ng-disabled="isLoading('group1', null)"><span class="spinner-transition" ng-class="{'spinner spinner--is-loading': isLoading('group1', '0')}"></span> Upload Files</button>

2 个答案:

答案 0 :(得分:0)

一些指针:

HTMLButton.Click btnInput.Value = "C:\temp\test.txt"应该在两行中。

HTMLButton.Click 
btnInput.Value = "C:\temp\test.txt"

我认为第二行是多余的。您的代码缺少与文件对话框进行交互以输入文件路径所需的更复杂的说明。整个问题的一个主题,已经在SO的其他地方解决了。

“按钮”是输入标签元素,您需要限制为适当的三个。

Dim uploads As Object, i As Long

Set uploads = ie.document.querySelectorAll("#examples [type=file]")

For i = 0 To uploads.Length-1
    uploads.item(i).click
    'other code
Next

我的建议是尝试使用实际的URL进行编码,并分享您在实际方案中遇到的问题。上面的代码IMO不适合用于给定的URL。

答案 1 :(得分:0)

我测试了它,但是它不起作用。我收到了运行时错误'-2147417848(80010108)。在循环行中单击F8后,被调用的对象已与其客户端断开连接。.根据您的建议,以下是新代码。是什么导致此问题?如果我以简单的“添加评论”的形式在此处发表评论,则表示歉意,不允许我放置代码。谢谢您的宝贵时间!

Private Sub CommandButton21_Click() Dim ie As Object Dim uploads As Object, i As Long Set ie = CreateObject("internetexplorer.application") ie.Visible = True ie.navigate "http://www.htmlquick.com/reference/tags/input-file.html" Do While ie.readyState <> 4 Loop Set uploads = ie.document.querySelectorAll("#examples [type=file]") For i = 0 To uploads.Length - 1 uploads.Item(i).Click'other code Next End Sub