使用Visual Basic在IE中获取当前URL

Llo*_*nks 6 url internet-explorer vba

我正在使用Visual Basic中的Internet Explorer对象.有没有办法复制IE正在显示的当前URL,所以我可以用剪贴板将其粘贴到其他地方?

Gaf*_*ffi 6

假设您已经识别出IE窗口,这本身就有点复杂了 - 如果需要,我可以详细说明:

Dim ieIEWindow As SHDocVw.InternetExplorer
Dim sIEURL As String

'Set your IE Window

sIEURL = ieIEWindow.LocationURL
Run Code Online (Sandbox Code Playgroud)

要获取IE窗口,您需要在VBA编辑器中引用Microsoft Internet Controlslibrary(ieframe.dll),方法是转到Tools=> References...并从列表中选择它.如果该项目不可用,我的.dll文件位于C:\Windows\System32\ieframe.dll.

设置引用后,您将可以访问SHDocVw代码中的所谓库.

您可以使用以下内容(从我自己的工作代码中未经测试,修改/减少)获取IE窗口(假设只有一个打开):

Public Function GrabIEWindow() As SHDocView.InternetExplorer

Dim swShellWindows As New SHDocVw.ShellWindows
Dim ieOpenIEWindow As SHDocVw.InternetExplorer

    Set GrabIEWindow = Nothing

    ' Look at the URLs of any active Explorer windows 
    ' (this includes WINDOWS windows, not just IE)
    For Each ieOpenIEWindow In objShellWindows

        ' Check the I.E. window to see if it's pointed 
        ' to a web location (http)
        If Left$(ieOpenIEWindow.LocationURL, 4) = "http" Then
            ' If so, set this window as the one to use. 
            ' This will need to be modified to create
            ' a list if you want to select from more
            ' than one open window

            ' Optional grab the HWND for later reference...
            Dim lWindowID As Long
            lWindowID = ieOpenIEWindow.HWND

            Set GrabIEWindow = ieOpenIEWindow

            Exit Function
        End If

    Next OpenIEWindow 

End Function
Run Code Online (Sandbox Code Playgroud)

还可以修改以上内容以允许选择多个打开的IE窗口.