VBA:从现有的打开的Internet Explorer选项卡中复制数据/文本

时间:2018-08-01 14:39:23

标签: vba excel-vba parsing internet-explorer web-scraping

我正在尝试编写一个VBA代码,该代码允许我通过发送带有 CTRL + A CTRL + C 的现有IE标签来复制数据SendKey方法,然后将其粘贴到Excel上的工作表中。 我尝试了“从Web获取数据”,但是由于我需要输入用户名/密码并且无法设置getElementbyId行,因此该方法无效。 因此,我找到了一些代码,该代码扫描了一个已经处于活动状态的Internet Explorer会话的打开的选项卡,但是我想使VBA切换到匹配的选项卡,然后从该网站复制文本。

Sub AAA()

    marker = 0
    Set objShell = CreateObject("Shell.Application")
    IE_count = objShell.Windows.Count
    For x = 0 To (IE_count - 1)
        On Error Resume Next    ' sometimes more web pages are counted than are open
        my_url = objShell.Windows(x).Document.Location
        my_title = objShell.Windows(x).Document.Title
        If my_url Like "http://www.cnn.com" & "*" Then 'compare to find if the desired web page is already open
            Set ie = objShell.Windows(x)
            marker = 1
            Exit For
        Else
        End If
    Next
    If marker = 0 Then
        MsgBox ("A matching webpage was NOT found")
    Else
        'Switch to the tab that matched and Copy the text from this website..
    End If

End Sub

1 个答案:

答案 0 :(得分:1)

他是获取IE的一种方式

Option Explicit

Sub Sample()
    Dim ShellApp As Object, ShellWindows As Object
    Dim objIE As Object, objWin As Object
    Dim ieCaption As String

    Set ShellApp = CreateObject("Shell.Application")
    Set ShellWindows = ShellApp.Windows()

    '~~> Loop through the windows and check if it is IE
    For Each objWin In ShellWindows
        If (Not objWin Is Nothing) Then
            ieCaption = objWin.Name
            If ieCaption = "Internet Explorer" Then
                Set objIE = objWin
                Exit For
            End If
        End If
    Next

    Set ShellApp = Nothing

    '~~> If IE is found then wirk with that object
    If Not objIE Is Nothing Then
        With objIE
            Debug.Print .Document.Body.Innerhtml
        End With
    End If
End Sub