为什么我的VBA脚本表现得如此不可预测?

时间:2016-11-08 16:26:44

标签: excel vba excel-vba internet-explorer

我在vba脚本中做了一些IE自动化,出于某种原因

“设置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

我将网站更改为goggle,因为实际目标只能在我们的Intranet上访问。由于没有加载登录页面,sendKeys部分也无关紧要。

1 个答案:

答案 0 :(得分: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

您可以使用const = uName和Const = UPwd作为登录详细信息。