2016-11-08 45 views
0

我做在VBA脚本一些IE的自动化,以及由于某种原因,为什么我的VBA脚本表现得如此难以预测?

“设置IE =的CreateObject(” InternetExplorer.Application“)”

行我的代码似乎是循环的,因为它会有时会启动3-7个IE浏览器而不是一个。最令人烦恼的部分是它在我的机器上工作正常,但是当我通过电子邮件发送给其他人时,它通常无法正常运行。这里是我的脚本:

Private Sub LauncherButton_Click() 
'Here an instance of Internet Explorer is created, 
' and pointed at the login page 
Dim IE As InternetExplorer 
Set IE = CreateObject("InternetExplorer.Application") 
URL = "www.google.com" 
IE.Visible = True 
IE.Navigate URL 


'The script waits for Internet Explorer to finish loading 
Application.Wait Now + TimeValue("00:00:03") 

'Here the login info is taken from the user inputs and entered 
' login page 
ID = Worksheets("home").Range("B25") 
PW = Worksheets("home").Range("B26") 

Application.SendKeys ID, True 
Application.SendKeys "{TAB}", True 
Application.SendKeys PW, True 
Application.SendKeys "{TAB}", True 
Application.SendKeys "{TAB}", True 
Application.SendKeys "{TAB}", True 

'This command will 'click' the login button, it will remain 
' commented until a user with access can run the script 

'Application.SendKeys "~", True 

'After the login info is entered it is removed from memory 
Worksheets("home").Range("B25").Clear 
Worksheets("home").Range("B26").Clear 
ID = "" 
PW = "" 
End Sub 

我改变了网站,护目镜,因为实际的目标只是在我们的内部网络访问。 sendKeys部分也是不相关的,因为登录页面没有被加载。

+0

我建议使用微软库,Internet控件和HTML来使用正确的对象,并且使用readystate和status而不是3秒循环。也使用对象而不是发送密钥,所以'getElementByID(“UserName”)。value = ID' –

+0

谢谢,我正在研究它。一旦我做出这些更改,我将更新此帖子 –

+0

是否有另一种获取元素的方法?该html代码没有id或标签属性。 –

回答

0

有许多因素都在起作用:

当初始化函数VBA代码保持在该函数的环境。正如我今天发现的那样,IE在调用导航功能后调用一个新窗口。因此,您的VBA将返回连接已丢失。

尝试:

 

    Private Sub UserForm_Password_AfterUpdate() 
     set WebBrowser = New InternetExplorerMedium 
     WebBrowser.visible = True 
     WebBrowser.Navigate yourLoginPageURL 

     While WebBrowser.Busy = True 
      DoEvents 
     Wend 

     WebBrowser.Document.getElementById("UName").value = Worksheets("home").Range("B25") OR txtBoxUname.Text 
     WebBrowser.Document.getElementById("UPwd").value =  Worksheets("home").Range("B26") OR txtBoxPwd.text 
     Worksheets("home").Range("B25").Clear 
     Worksheets("home").Range("B26").Clear 
    End Sub 


    Private sub cboAddress_AfterUpdate() 
     if cboAddress.Text > "" then 
      WebBrowser.Quit 
      Set WebBrowser = Nothing 
      newIE 
     End If 
    End Sub 

    Private Sub newIE() 
     Set WebBrowser = CreateObject("InternetExplorer.Application") 
     With WebBrowser 
      Hwnd = .Hwnd 
      .Navigate cboAddress.Text 
      .Visible = True 
     End With 

     While WebBrowser.Busy 
      DoEvents 
     Wend 
    End Sub 

您可以使用常量= UNAME和const = UPwd为您的登录信息。

+0

感谢您的建议,我正在逐一实施。到目前为止,我已经经历了第一个子集,但是我非常间歇性地收到一个运行时错误,它说“对象变量或块变量未设置”。点击调试按钮突出显示第一个getElement行。 –

+0

打开一个空白页面开始。导航到第一个实例的页面。然后,关闭每个浏览器连接并使用每个新导航创建新的Internet Explorer对象! –

+0

这是我刚刚做的一个项目。在Excel文件中使用IE链接表单。它会加载一个空白的Internet Explorer窗口,然后您可以在Web链接下拉列表中选择一个地址以导航到表单,然后在表单的功能下拉列表中选择导航到。 –

相关问题