使用VBA直接从Internet Explorer打开CSV文件时,我无法与该文件进行交互。

时间:2018-02-14 12:56:10

标签: vba excel-vba web-scraping excel

所以我编写了一些代码,通过模拟按钮点击从twitter下载分析数据。这不是很漂亮的代码,但我现在可以找到它。

我成功地点击了文件下载,然后出现带有打开的保存选项的“框架通知栏”。我成功地点击了两次打开,但这是我遇到问题的地方。问题是我然后想要与我刚刚选择打开的CSV文件中的数据进行交互,但是在代码完成运行之后,CSV文件才会出现。我知道必须有一个简单的解决方案,但我只是不知道要搜索什么。

我曾尝试使用Wait和DoEvents来查看是否有帮助但到目前为止没有运气。这是我的代码:

Private Sub CommandButton1_Click()

UserForm1.Hide
Dim appIE As Object
Set appIE = CreateObject("internetexplorer.application")


With appIE
    .Navigate "https://analytics.twitter.com/user/QinetiQ/tweets"
    .Visible = True
End With
Do While appIE.Busy
    DoEvents
Loop
Application.Wait (Now + TimeValue("0:00:04"))

Set HTMLDoc = appIE.document
    Set btn = HTMLDoc.getElementsByClassName("btn btn-default ladda-button")(0)
    btn.Click
    Application.Wait (Now + TimeValue("0:00:07"))
    Application.SendKeys "%{S}"

Dim o As IUIAutomation
    Dim e As IUIAutomationElement
    Set o = New CUIAutomation
    Dim h As Long
    h = appIE.Hwnd
    h = FindWindowEx(h, 0, "Frame Notification Bar", vbNullString)
    If h = 0 Then Exit Sub
    Set e = o.ElementFromHandle(ByVal h)
    Dim iCnd As IUIAutomationCondition
    Set iCnd = o.CreatePropertyCondition(UIA_NamePropertyId, "Open")
    Dim Button As IUIAutomationElement
    Application.Wait (Now + TimeValue("0:00:03"))
    SendKeys "%(o)"
    Dim wb As Workbook
    DoEvents

    Application.Wait (Now + TimeValue("0:00:15"))
    Set wb = GetWB
    Dim ws As Worksheet
    Set ws = wb.ActiveSheet

End Sub

Function GetWB() As Workbook
    Dim wb As Workbook
 wbName = "tweet"

    For Each wb In Application.Workbooks
        If wb.Name Like wbName & "*" Then
            Set GetWB = wb
            MsgBox ("Found it")
            Exit Function
        End If
    Next wb
    MsgBox ("failed to find worksheet")
End Function

我知道我已经使用了一些非常糟糕的技术并为此道歉。请任何人帮忙,谢谢你。

1 个答案:

答案 0 :(得分:0)

您可以使用Application.OnTime将宏分成两部分 - 这样您就可以完成宏(以便CSV文件可以打开),然后安排一个新的宏在几秒钟后启动:< / p>

    'This is the end of CommandButton1_Click
    Application.Wait (Now + TimeValue("0:00:03"))
    SendKeys "%(o)"
     Dim wb As Workbook
     DoEvents

    Application.OnTime Now()+TimeSerial(0,0,15), "ContinueDownloadMacro"
    'In 15 seconds the "ContinueDownloadMacro" Sub will start
End Sub

Public Sub ContinueDownloadMacro()
    Dim wb As Workbook, ws As Worksheet

    Set wb = GetWB
    Set ws = wb.ActiveSheet

End Sub