如何从网页上的下拉菜单中选择值:VBA

时间:2016-06-07 20:42:12

标签: excel vba excel-vba

enter image description here 我的代码:

Sub login()
  Dim IE As Object
  Dim HTMLDoc As Object, HTMLDoc2 As Object
  Dim objCollection As Object

  Const navOpenInNewTab = &H800
  Set IE = CreateObject("InternetExplorer.Application")
  IE.Visible = True
  IE.Navigate "https:/com/1/19/login.esp"

  Do While IE.Busy Or IE.ReadyState <> 4: Loop

  Set HTMLDoc = IE.Document

  With HTMLDoc
  HTMLDoc.getElementById("USERNAME").Value = "xxxx"    'Entering credential
  HTMLDoc.getElementById("PASSWORD").Value = "yyyyy"
  End With


  Set objCollection = IE.Document.getElementById("loginbutton")
  objCollection.Click

 'Second webpage

  Do While IE.Busy Or IE.ReadyState <> 4: Loop ' opening the second webpage

  Set HTMLDoc2 = IE.Document
  With HTMLDoc2
  **HTMLDoc2.getElementById("DEPARTMENTID").selectedindex = 1  'Drop down menu
  HTMLDoc2.getElementById("DEPARTMENTID").FireEvent ("onchange")**
  End With

  Set objCollection = IE.Document.getElementById("loginbutton")
  objCollection.Click

End Sub

Q)我选择Dwell_DF选项值1567进行哪些代码更改? 上面的代码给出了运行时错误&#39;&#39;&#39; :需要对象。

 HTMLDoc2.getElementById("DEPARTMENTID").selectedindex = 1  'Drop down menu
          HTMLDoc2.getElementById("DEPARTMENTID").FireEvent ("onchange")

以上行给出错误。

在第一个网页中,我填写了登录凭据,然后在下一页中粘贴了此帖子粘贴的图像。在这里,我想更改下拉菜单中的值。

2 个答案:

答案 0 :(得分:0)

试一试。价值&#34; 1567&#34;对应于InnerText&#34; Dwell_DF&#34;。

With HTMLDoc2
    .getElementById("DEPARTMENTID").Focus
    .getElementById("DEPARTMENTID").Value = "1567"  'You can also loop to find the text of the Option
    .getElementById("DEPARTMENTID").FireEvent ("onchange")
End With

答案 1 :(得分:0)

它应该是这样的。

Sub passValueToComboBox1()
   Dim ie  As Object
   Dim oHTML_Element As IHTMLElement

   Set ie = CreateObject("InternetExplorer.Application")
   ie.Visible = True
   ie.navigate "http://your_URL_here.php"
   While ie.Busy Or ie.readyState <> 4: DoEvents: Wend

   Set oHTML_Element = ie.document.getElementsByName("selectedReportClass")(0)
   If Not oHTML_Element Is Nothing Then oHTML_Element.Value = "FUBU7"

   For Each oHTML_Element In ie.document.getElementsByTagName("input")
      If oHTML_Element.Type = "submit" Then oHTML_Element.Click: Exit For
   Next
End Sub

请查看以下链接,了解有关如何以编程方式与网站进行互动的其他一些建议。

http://vbadud.blogspot.com/2009/08/how-to-login-to-website-using-vba.html