VBA Excel input data into already opened ie window

空扰寡人 提交于 2020-06-17 07:57:09

问题


I have here a very simple example when pressing button1 will open a new ie window and into google search inputs "cheap plastic windows". What I want to do is when I press button2 the text in google search (already opened ie window) changes to "cheap plastic doors". I have been trying to do it for 2 days but can not seem to find how to. Would appreciate if you could help with a working example. Thank you

Private Sub CommandButton1_Click()

Set objIE = CreateObject("InternetExplorer.Application")

objIE.Visible = True

objIE.Navigate ("www.google.co.uk")

Do 

DoEvents

Loop Until objIE.ReadyState = 4

objIE.Document.GetElementById("lst-ib").Value = "cheap plastic windows"

End Sub

Private Sub CommandButton2_Click()
'the command below does not as obviously the objIE is not select which I have no idea how to do

ie.Document.GetElementById("lst-ib").Value = "cheap plastic doors"

End Sub

回答1:


You can use this, which checks to make sure the window is there, if so it finds it and types in it. There is a small risk that if the user goes to another application before click on "CommandButton2" that it may not work. But if the user stays on your macro and IE only it will work.

Private Sub CommandButton2_Click()

      Dim ie As Object

      With CreateObject("Shell.Application").Windows

        If .Count > 0 Then
          ' Get IE
          Set ie = .Item(.Count - 1)
        Else
          ' Create IE
          Set ie = CreateObject("InternetExplorer.Application")
          ie.Visible = True
        End If

      End With

      ie.Document.GetElementById("lst-ib").Value = "cheap plastic doors"

      Set ie = Nothing

End Sub


来源:https://stackoverflow.com/questions/39794951/vba-excel-input-data-into-already-opened-ie-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!