# VBA Macro For Already Open IE Window



## RL101

Hi all,

I'm looking to create a VBA macro which will be ran from Excel (2003 or 2010) & which works with Internet Explorer. I have added 'Microsoft Internet Controls' to VBA References, and have looked at plenty of VBA code on the forum which opens & then navigates to specific websites. 

However, what I need is for this macro to affect an already open IE window.

Does anyone have an idea of the syntax / command to have excel "select" a specific IE window already open? 

Many thanks!


----------



## ZVI

Hi & Welcome to the Board!
Try this:


		Rich (BB code):
__



' ZVI:2011-05-30 http://www.mrexcel.com/forum/showthread.php?t=553580
' Reference required: Tools - References - Microsoft Internet Controls
Sub GetIE()
  
  Dim shellWins As ShellWindows
  Dim IE As InternetExplorer

  Set shellWins = New ShellWindows

  If shellWins.Count > 0 Then
    ' Get IE
    Set IE = shellWins.Item(0)
  Else
    ' Create IE
    Set IE = New InternetExplorer
    IE.Visible = True
  End If

  IE.Navigate "http://support.microsoft.com/kb/q176792/"

  Set shellWins = Nothing
  Set IE = Nothing

End Sub

Regards,


----------



## ZVI

The same, but with more correct code lines order for memory releasing at the end of subroutine:


		Rich (BB code):
__



' ZVI:2011-05-30 http://www.mrexcel.com/forum/showthread.php?t=553580
' Reference required: Tools - References - Microsoft Internet Controls
Sub GetIE()
  
  Dim shellWins As ShellWindows
  Dim IE As InternetExplorer

  Set shellWins = New ShellWindows

  If shellWins.Count > 0 Then
    ' Get IE
    Set IE = shellWins.Item(0)
  Else
    ' Create IE
    Set IE = New InternetExplorer
    IE.Visible = True
  End If

  IE.Navigate "http://support.microsoft.com/kb/q176792/"

  Set IE = Nothing
  Set shellWins = Nothing

End Sub


----------



## ZVI

Late binding version, reference to Microsoft Internet Controls is not required:


		Rich (BB code):
__



Sub GetIE_LateBinding()
  
  Dim IE As Object
  
  With CreateObject("Shell.Application").Windows
    
    If .Count > 0 Then
      ' Get IE
      Set IE = .Item(0) ' or .Item(.Count - 1)
    Else
      ' Create IE
      Set IE = CreateObject("InternetExplorer.Application")
      IE.Visible = True
    End If
  
    IE.Navigate "http://support.microsoft.com/kb/q176792/"
  
    Set IE = Nothing
  
  End With
  
End Sub

P.S. Window of any MS Explorer can be catched, not only of MS Internet Explorer.


----------



## nbraybrook

Hello, new to the forums! I am trying to use this code to either open explorer to the page I want or if the user already has that page open in IE I want it to just bring it forward. Problem I am having is while this macro will open IE to the page, if say, I already have that page open it is just opening a new tab of the same page every time I click it.


----------



## ZVI

nbraybrook said:


> Hello, new to the forums! I am trying to use this code to either open explorer to the page I want or if the user already has that page open in IE I want it to just bring it forward. Problem I am having is while this macro will open IE to the page, if say, I already have that page open it is just opening a new tab of the same page every time I click it.


Hi & Welcome to the Board!
Try this code:


		Rich (BB code):
__



Function NavigateTo(Link As String, Optional WaitSeconds = 5) As Long
' ZVI:2011-08-04 http://www.mrexcel.com/forum/showthread.php?t=553580
' Navigate (Internet)Explorer to the Link with [WaitSeconds=5] timeout.
' If (Internet)Explorer is already navigated to the Link then it's just activated,
' else the new (Internet)Explorer is navigated to the Link.
' Returns  error number (zero at success)
' Note: comment "Application.StatusBar" lines for VB & VBScript compatibility

  Dim i As Long, t As Single, Url As String, w As Object, wUrl As String
  
  ' Uniform Link string
  Url = Trim(Replace(Replace(Link, "%20", " "), "\", "/"))
  ' Find "://" prefix
  i = InStr(Url, "://")
  If i > 1 And i < 7 Then Url = Mid(Url, i + 3)
  ' Delete "/" at the end
  If Right(Url, 1) = "/" Then Url = Left(Url, Len(Url) - 1)
    
  ' Seach Link in IE windows
  Application.StatusBar = "Finding link: " & Link & " ..."
  For Each w In CreateObject("Shell.Application").Windows
    ' Uniform LocationURL string
    wUrl = Trim(Replace(Replace(w.LocationURL, "%20", " "), "\", "/"))
    ' Find "://" prefix
    i = InStr(wUrl, "://")
    If i > 1 And i < 7 Then wUrl = Mid(wUrl, i + 3)
    ' Del 3d "/" in prefix for local Link
    If Mid(wUrl, 1, 1) = "/" Then wUrl = Mid(wUrl, 2)
    ' Delete "/" at the end
    If Right(wUrl, 1) = "/" Then wUrl = Left(wUrl, Len(wUrl) - 1)
    If StrComp(Url, wUrl, 1) = 0 Then
      ' Link is found - activate it's IE window
      w.Visible = True
      Exit For
    Else
       wUrl = ""
    End If
  Next
  
  ' If Link is not found then create new IE and navigate to the Link
  On Error Resume Next
  If Len(wUrl) = 0 Then
    With CreateObject("InternetExplorer.Application")
      ' Disable pop-up msgs
      .Silent = True
      ' Navigate
      Application.StatusBar = "Navigating to: " & Link & " ..."
      .Navigate Link
      ' Charge the timeout
      t = Timer + WaitSeconds
      ' Wait for "IE is ready" state
      Application.StatusBar = "Waiting for IE's complete state..."
      While .readyState <> 4 And Timer < t: DoEvents: Wend
      ' Wait for "IE.Document is completely downloaded" state
      If Timer < t Then
        Application.StatusBar = "Waiting for Document's downloaded state..."
        While .Document Is Nothing And Timer < t: DoEvents: Wend
      Else
        Err.Raise vbObjectError + 513, , "Timeout happens: " & WaitSeconds & " seconds"
      End If
      ' Activate IE
      Application.StatusBar = False
      If Err Then .Quit Else .Visible = True
    End With
  End If
  
  ' Release the memory of object variable
  Set w = Nothing
  
  ' Return error number (zero if successful)
  NavigateTo = Err.Number
  
  ' Show error message
  If Err.Number <> 0 Then
    Application.StatusBar = "NavigateTo: " & Replace(Err.Description, vbLf, " - ")
    ' Uncomment the line below to show error message
    'MsgBox Err.Description, vbExclamation, "NavigateTo"
  End If
  
End Function


Example of the calling:


		Rich (BB code):
__



Sub Test_NavigateTo()
  
  ' Define the test number
  Const TEST = 2
  
  Select Case TEST
    Case 1: NavigateTo "about:blank"
    Case 2: NavigateTo "www.mrexcel.com/forum/showthread.php?t=553580"
    Case 3: NavigateTo "http://www.google.com/"
    Case 4: NavigateTo "http://support.microsoft.com/kb/q176792/"
    Case 5: NavigateTo "C:\Temp"
  End Select
  
End Sub


----------



## SpoolinUp

Hello all!

I am trying to do similar to the above but cannot get an addition to the code working.

Basically I want excel to automatically open a browser window, then in the same instance navigate to a web page every 5 minutes or so. A simple refresh won't work on this page unfortunately, so I have to have it navigate to the root page every time rather than refresh. I've never used the timer function and am not having great luck, a little help would be much appreciated!

Thanks!!

-Matt


----------



## ZVI

SpoolinUp said:


> Hello all!
> 
> I am trying to do similar to the above but cannot get an addition to the code working.
> 
> Basically I want excel to automatically open a browser window, then in the same instance navigate to a web page every 5 minutes or so. A simple refresh won't work on this page unfortunately, so I have to have it navigate to the root page every time rather than refresh. I've never used the timer function and am not having great luck, a little help would be much appreciated!
> 
> Thanks!!
> 
> -Matt


Hi Matt,
Welcome to the Board!
 Seems it's a bit different task, hope you mean something like this:


		Rich (BB code):
__


' Code of Module1

Sub LoopIE(Optional Cancel As Boolean)
  
  ' --> Settings, change to suit
  Const Link = "www.google.com"
  Const RepeatMinutes = 5   ' Time interval in minutes for repeating of this macro
  Const WaitSeconds = 10    ' Waiting time interval in secondss for "IE is ready" state
  ' <-- End of settings

  Dim t As Single
  Static IE As Object, t1 As Double
  
  ' Cancel the repeating of this macro
  If Cancel Then
    ' Cancel schedule
    If t1 Then Application.OnTime t1, "LoopIE", Schedule:=False
    t1 = 0
    ' Reset IE object
    On Error Resume Next
    If Not IE Is Nothing Then IE.Quit
    Set IE = Nothing
    Exit Sub
  End If
  
  ' Trap error
  On Error GoTo exit_

  ' Main
  If IE Is Nothing Then Set IE = CreateObject("InternetExplorer.Application")
  With IE
    .Visible = True
    ' Disable pop-up msgs
    .Silent = True
    ' Navigate
    Application.StatusBar = "Navigating to: " & Link & " ..."
    .Navigate Link
    ' Charge the timeout
    t = Timer + WaitSeconds
    ' Wait for "IE is ready" state
    Application.StatusBar = "Waiting for IE's complete state..."
    While .readyState <> 4 And Timer < t: DoEvents: Wend
    ' Wait for "IE.Document is completely downloaded" state
    If Timer < t Then
      Application.StatusBar = "Waiting for Document's downloaded state..."
      While .Document Is Nothing And Timer < t: DoEvents: Wend
    Else
      Err.Raise vbObjectError + 513, , "Timeout happens: " & WaitSeconds & " seconds"
    End If
  End With

exit_:

  ' Inform about error
  If Err.Number <> 0 Then
    Application.StatusBar = "NavigateTo: " & Replace(Err.Description, vbLf, " - ")
    ' Show error message
    MsgBox Err.Description, vbExclamation, "Error"
    ' Reset IE object
    On Error Resume Next
    If Not IE Is Nothing Then IE.Quit
    Set IE = Nothing
  Else
    ' Clear StatusBar
    Application.StatusBar = False
    ' Charge schedule
    t1 = Now + TimeSerial(0, RepeatMinutes, 0)
    Application.OnTime t1, "LoopIE"
  End If

End Sub

' Macro for the Start button
Sub Start()
  LoopIE
End Sub

' Cancel schedule and quit IE
Sub Auto_Close()
  LoopIE Cancel:=True
End Sub


Regards


----------



## SpoolinUp

Works great Vladimir! Just one hiccup non-related to your great work. I use the program to keep me actively logged into a website that will auto-timeout the login after 10 minutes. On one system running Windows 7, it logs me out every time it refreshes. Any thoughts? Thanks again.


----------



## ZVI

SpoolinUp said:


> Works great Vladimir! Just one hiccup non-related to your great work. I use the program to keep me actively logged into a website that will auto-timeout the login after 10 minutes. On one system running Windows 7, it logs me out every time it refreshes. Any thoughts? Thanks again.


You are welcome, Matt! 
As to that program, if it's VBA program then we need to look onto its code.
If not then may be its support team helps.
Good luck!


----------



## RL101

Hi all,

I'm looking to create a VBA macro which will be ran from Excel (2003 or 2010) & which works with Internet Explorer. I have added 'Microsoft Internet Controls' to VBA References, and have looked at plenty of VBA code on the forum which opens & then navigates to specific websites. 

However, what I need is for this macro to affect an already open IE window.

Does anyone have an idea of the syntax / command to have excel "select" a specific IE window already open? 

Many thanks!


----------



## skybound7

Wanted to thank you for your post. It came in very helpful today.


----------



## ZVI

skybound7 said:


> Wanted to thank you for your post. It came in very helpful today.


Welcome to MrExcel, Skybound!
And thank you for the response. I also learn here a lot every time


----------



## jonaskp

Hi,

I have a similar problem and have tried using the code in this thread, but cannot get it to work. I

I want to switch (from my userform) to a specific open Internet Explorer window. I know the title of the window (like on this thread the title is "VBA Macro for already open IE Window... etc."). Can I use that combined with your code to always switch to this open window?

Thanks in advance.


----------



## ZVI

jonaskp said:


> Hi,
> 
> I have a similar problem and have tried using the code in this thread, but cannot get it to work. I
> 
> I want to switch (from my userform) to a specific open Internet Explorer window. I know the title of the window (like on this thread the title is "VBA Macro for already open IE Window... etc."). Can I use that combined with your code to always switch to this open window?
> 
> Thanks in advance.


 Hi and welcome to MrExcel!
Try this:


		Rich (BB code):
__



' ZVI:2012-12-19 Activating of IE window by its title
' Arguments:
'   Title     -  title of the searchied IE window
'   [IsLike]  -  False/True = exact/partial searching, default is False
Sub ActivateIeByTitle(Title, Optional IsLike As Boolean)
  Dim w As Object
  For Each w In CreateObject("Shell.Application").Windows
    With w
      If .Name = "Windows Internet Explorer" Then
        If IsLike Then
          If InStr(1, .LocationName & " - " & .Name, Title, vbTextCompare) > 0 Then
            ' Partial title of window is found - activate IE window
            w.Visible = False
            w.Visible = True
            Exit For
          End If
        Else
          If StrComp(.LocationName & " - " & .Name, Title) = 0 Then
            ' Title of window is found - activate IE window
            w.Visible = False
            w.Visible = True
            Exit For
          End If
        End If
      End If
    End With
  Next
  Set w = Nothing
End Sub
 
Sub Test1()
  ' Activate IE's window by exact searching in titles
  ActivateIeByTitle "VBA Macro For Already Open IE Window#post3345848 - Windows Internet Explorer"
End Sub
 
Sub Test2()
  ' Activate IE's window by partial searching in titles
  ActivateIeByTitle "VBA Macro For Already Open IE Window", True
End Sub

Regards,


----------



## ericm76903

Hello,
Like with every one else, I am a new member. But this thread seems to be the area I am looking for.

Here is what I have.

I have an IE window opened. And I know the name of the window.

I need the marco to be able to access that object, so I can do something like set a value within the IE window. The setting of this value will trigger an action on the page, like a script that does an alert or something. Can a combination of the previous macros do that?

Thank you in advance,
Eric


----------



## ZVI

ericm76903 said:


> I have an IE window opened. And I know the name of the window.
> I need the marco to be able to access that object, so I can do something like set a value within the IE window. The setting of this value will trigger an action on the page, like a script that does an alert or something.


Hi Eric, 
Welcome to MrExcel !
Function GetIeByTitle finds IE window by window title and returns IE object.
See example of the usage in Test1 subroutine.


		Rich (BB code):
__



' ZVI:2013-03-19 Get IE object of already open window by its title
' Arguments:
'   Title     -  title of the searchied IE window
'   [IsLike]  -  False/True = exact/partial searching, default is False
'   [IsFocus] -  False/True = don't_activate/activate IE window, default is False
Function GetIeByTitle(Title, Optional IsLike As Boolean, Optional IsFocus As Boolean) As Object
  Dim w As Object
  For Each w In CreateObject("Shell.Application").Windows
    With w
      If .Name = "Windows Internet Explorer" Then
        If IsLike Then
          If InStr(1, .LocationName & " - " & .Name, Title, vbTextCompare) > 0 Then
            ' Partial title of window is found - activate IE window
            If IsFocus Then
              w.Visible = False
              w.Visible = True
            End If
            Set GetIeByTitle = w
            Exit For
          End If
        Else
          If StrComp(.LocationName & " - " & .Name, Title) = 0 Then
            ' Title of window is found - activate IE window
            If IsFocus Then
              w.Visible = False
              w.Visible = True
            End If
            Set GetIeByTitle = w
            Exit For
          End If
        End If
      End If
    End With
  Next
  Set w = Nothing
End Function
 
Sub Test1()
  Dim IE As Object
  Set IE = GetIeByTitle("VBA Macro For Already Open IE Window", True, True)
  IE.Navigate "http://www.mrexcel.com/forum/excel-questions/553580-visual-basic-applications-macro-already-open-ie-window-2.html#post3423470"
End Sub

Regards


----------



## ZVI

Another version of Test1 with error trapping:


		Rich (BB code):
__


Sub Test1()
  Dim IE As Object
  Const Title = "VBA Macro For Already Open IE Window"
  Const URL = "http://www.mrexcel.com/forum/excel-questions/553580-visual-basic-applications-macro-already-open-ie-window-2.html#post3423470"
  Set IE = GetIeByTitle(Title, True, True)
  If IE Is Nothing Then
    MsgBox "Window is not found:" & vbLf & Title, vbCritical, "Error"
  Else
    IE.Navigate URL
  End If
End Sub


----------



## jonaskp

I can see that I somehow completely forgot about this thread.

Thank you very much ZVI for your solution to my problem a while back. It is working perfectly.


----------



## ZVI

jonaskp said:


> I can see that I somehow completely forgot about this thread.
> 
> Thank you very much ZVI for your solution to my problem a while back. It is working perfectly.


I'm happy to know it has helped 
Thank you for the feedback!


----------



## bkclaw113

The responses in this thread have been great, so here is hoping that ZVI is still monitoring.

I used your late binding code as a basis to create this simple tester sub:


		Code:
__


Sub ActivateIeByTitle(Title)
  Dim w As Object
  For Each w In CreateObject("Shell.Application").Windows
      If w.Name = "Windows Internet Explorer" Then
            Debug.Print w.locationname
            If w.locationname Like (Title & "*") Then
                w.Visible = False
                w.Visible = True
                Debug.Print "IE Page located"
                GoTo exit_sub
                
            End If
      End If
  Next
    Debug.Print "IE Page Not located"
exit_sub:
  Set w = Nothing
End Sub


The code runs fine on the two computers that I use (Windows XP with Excel 2007 SP3, and Windows 7 with Excel 2007 SP3), however it does not run on a colleagues comptuer who is also running Windows 7 with Excel 2007 SP3.


The Error "Method 'Windows' of object 'IShellDispatch5' Failed" is thrown on the line 
	
	
	
	
	
	




		Code:
__


For Each w In CreateObject("Shell.Application").Windows

.

Any suggestions on what might be the issue or how to resolve it?


----------



## RL101

Hi all,

I'm looking to create a VBA macro which will be ran from Excel (2003 or 2010) & which works with Internet Explorer. I have added 'Microsoft Internet Controls' to VBA References, and have looked at plenty of VBA code on the forum which opens & then navigates to specific websites. 

However, what I need is for this macro to affect an already open IE window.

Does anyone have an idea of the syntax / command to have excel "select" a specific IE window already open? 

Many thanks!


----------



## ZVI

Hi *bkclaw113*, Welcome aboard! By the way, the 7th greeting of new member in this thread! 

CreateObject("Shell.Application") in XP involves IDispatch4 for creating ShellWindows object.
Not sure what is IDispatch5 for, but googling says it sometimes can be in Vista or in Win7.

On my PC code works fine in Win7 64bit with Excel 2003,2007 32 bit and with 2013 64 bit.
IDispatch5 was not found in the registry of my PC at all.

If code runs fine on the two computers then something is wrong on colleagues computer.
It is impossible to say exactly what is wrong without debugging the problem.
Thus - just guessing.

The differences between working and not working PCs can be in registry item HKEY_CLASSES_ROOT\CLSID\{13709620-C279-11CE-A49E-444553540000}.
Hope, you might compare and fix it. 

Without registry fixing, in the code
instead of: CreateObject("Shell.Application").Windows
try one of these:
1. CreateObject("Shell.Application*.1*").Windows
2. GetObject("New:{13709620-C279-11CE-A49E-444553540000}").Windows 

Let us know if ledge-hammer cracked nuts 

Regards


----------



## bkclaw113

Thanks for the quick reply.  I was able to test the non-registry suggestions that you provided and I am still experiencing the issue on the one computer.  I will explore the registry settings and see if I can resolve the issue that way.

Again really appreciate the quick and detailed response.


----------



## ZVI

Thank you for the feedback!
Please try testing the late binding version of your code.
This code requires reference to: VBE – menu Tools – References - Microsoft Internet Controls


		Rich (BB code):
__


Sub Test()
  ActivateIeByTitle1 "VBA Macro For Already Open IE Window"
End Sub
 
' Reference required: Tools - References - Microsoft Internet Controls
Sub ActivateIeByTitle1(Title)
  Dim shellWins As ShellWindows
  Dim w As InternetExplorer
  Set shellWins = New ShellWindows
  For Each w In shellWins
    If w.Name = "Windows Internet Explorer" Then
      Debug.Print w.locationname
      If w.locationname Like (Title & "*") Then
        w.Visible = False
        w.Visible = True
        Debug.Print "IE Page located"
        GoTo exit_sub
      End If
    End If
  Next
  Debug.Print "IE Page Not located"
exit_sub:
  Set w = Nothing
End Sub


----------



## bkclaw113

At the step 
	
	
	
	
	
	




		Code:
__


[COLOR=#00008b]Set[/COLOR] shellWins = [COLOR=darkblue]New[/COLOR] ShellWindows

 we are getting an error:*Run-time error '-2147024894 (80070002)':
Automation error
The system cannot find the file specified.
*​I compared the registry entries and he has version 1.1 where I have version 1.0. I am going to try to test on some more computers and see if the registry values hold true for when the code works verse not. Even if I do find a pattern I think I will have an up hill battle getting the desktop support folks to fix anything. As always thanks for the assistance.


----------



## ZVI

Then you set reference to *Microsoft Internet Controls* it may reference to *ieframe.dll*
Sometimes this can raise an issue, seems it somehow depends from IE installation/updating. 
For this case try:
1. Uncheck reference: *VBE – menu Tools – References - Microsoft Internet Controls* and press *OK* to close References window
2. Open *References* window again and use *Browse* button to choose in folder *Windows\System32* the file *shdocvw.dll* and press OK.
    Reference to *Microsoft Internet Controls* should be set via *shdocvw.dll*
3. Run the code of post#23 to see if it works


----------



## bkclaw113

Unfortunately this suggestion did not help either.  I have some changes to my program that make this process no longer critical so I am afraid that I am going to need to leave this unsolved and focus on other priorities for the time being.  Thanks for all of your effort.


----------



## ZVI

Thank you for the back response, it's sad the problem was not solved. 

But at least we know now that early binding is not working at all.
  Therefore the culprit is neither Excel nor the code. Something is wrong with system DLLs or their registration. 
Just for the case, I would recommend reinstalling/updating IE on that PC.

Happy to know you've found the way to minimize dependence of that part of code in your program. 
Good luck!


----------



## Jamez007

Hi,

I am trying to use the code provided by ZVI with the following title "ZVI:2011-08-04 VBA Macro For Already Open IE Window".  I am having an issues in Win 7, IE 9 when trying to access a local htm file with javascript on it.  The javascript causes IE to popup an alert saying it is restricting the script from running etc.  This messes .readyState property, which results in an endless while loop where the timeout condition is ignored .  Google works, but not my local htm file because IE prevents the script from running, resulting in a warning "The remote server machine does not exist or is unavailable".

Can I use VBA to get around this error without changing the default IE protection settings that the user will need for every day usage?

Thanks,
Alex


----------



## l_rosete22

Hello, 

I am new here and this post is really helping.

I am using a combinations of codes from this board. I need help honestly. Is any one want to help me!
These are my objectives:

I'm doing it in a Excel userForm

1. Login in a webpage. - Validates if username and password is correct. ELSE repeat login or renter username/password.

- Assuming login success - Manually close IE then Click Login button again.
2. The IE should open then inform user that he is already logged in.

-Assuming that the IE left idle and the page expired. there is a link appear "click here" to log off
  Note: Need to log off and close IE to be able to login again.
3. Validate if page if expired then close IE then, Open IE and navigate to login page.

Anyone help me to code this? I am really in trouble.

Thank you in advance,


----------



## ZVI

l_rosete22 said:


> I am using a combinations of codes from this board


Hi,

It seems that your request is out of the thematic of this thread, mentioned in the title.

Therefore it is better to create new thread with posting of your existing code and description of the problematic parts.
Please take into account that web pages are mostly unique and there are no universal rules & code for their control or parsing.
 That is, VBA code will depend from the source code and the engine of the particular web page.
And access to that particular web page is required for the debugging.
So to give someone a chance to help you, please provide in the new thread as many details as possible.

Good luck!


----------



## RL101

Hi all,

I'm looking to create a VBA macro which will be ran from Excel (2003 or 2010) & which works with Internet Explorer. I have added 'Microsoft Internet Controls' to VBA References, and have looked at plenty of VBA code on the forum which opens & then navigates to specific websites. 

However, what I need is for this macro to affect an already open IE window.

Does anyone have an idea of the syntax / command to have excel "select" a specific IE window already open? 

Many thanks!


----------



## Excel_Phil

Hello Guys,

Im kinda new to VBA. Im trying to get codes from posts #6 and #16 to work, but I cant. Where do I need to type my URLs? Or in the case of window title, I type it in: "VBA Macro For Already Open IE Window - Page 2" but it wont work. Am I getting the title page wrong? Am I not typing it in somewhere in the function or in the code? I have the function and the subs in the same module, it is something wrong with that?

In references, I have added Microsoft Internet Controls and I have no "missing anything." I just cant understand how to get the code to work.

Thanks in advance!!


----------



## ZVI

Hi Phil, welcome to MrExcel!

Well, lets's test the finding of IE window by its title. 

Do as follows:

1. Select and copy all the below code to the clipboard.
2. In *VBE* use menu *Insert* - *Module* to create *Module1*
3. Paste from the clipboard the code of the function *GetIeByTitle* to that module
 4. Open IE on this page  http://www.mrexcel.com/forum/excel-...pplications-macro-already-open-ie-window.html
5. Run the *Test_GetIeByTitle* - the IE window have to be found. Message will inform about success. 
6. Close that IE window and run again *Test_GetIeByTitle* - IE window shall not be found, error message will appear. 




		Rich (BB code):
__


' ZVI:2013-09-10 Get IE object of already open window by its title
' Arguments:
'   Title     -  title of the searchied IE window
'   [IsLike]  -  False/True = exact/partial searching, default is False
'   [IsFocus] -  False/True = don't_activate/activate IE window, default is False
Function GetIeByTitle(Title, Optional IsLike As Boolean, Optional IsFocus As Boolean) As Object
  Dim w As Object
  For Each w In CreateObject("Shell.Application").Windows
    With w
      If .Name = "Windows Internet Explorer" Then
        If IsLike Then
          If InStr(1, .LocationName, Title, vbTextCompare) > 0 Then   ' ZVI:2013-09-10 fixed
            ' Partial title of window is found - activate IE window
            If IsFocus Then
              w.Visible = False
              w.Visible = True
            End If
            Set GetIeByTitle = w
            Exit For
          End If
        Else
          If StrComp(.LocationName & " - " & .Name, Title, 1) = 0 Then  ' ZVI:2013-09-10 fixed
            ' Title of window is found - activate IE window
            If IsFocus Then
              w.Visible = False
              w.Visible = True
            End If
            Set GetIeByTitle = w
            Exit For
          End If
        End If
      End If
    End With
  Next
  Set w = Nothing
End Function
 
' Testing subroutine for the above function GetIeByTitle.
'
' 1. Try this macro with already open IE window on this page:
'    http://www.mrexcel.com/forum/excel-questions/553580-visual-basic-applications-macro-already-open-ie-window.html
'    Macro should successfuly find the IE window by its Title.
'
' 2. Close that IE window and try the code again - IE window will not be found.
'    Error message will appear.
'
Sub Test_GetIeByTitle()
  Dim IE As Object
  Dim Title As String
  Title = "VBA Macro For Already Open IE Window"
  Set IE = GetIeByTitle(Title, True, True)
  If IE Is Nothing Then
    MsgBox "IE window with this Title is not found:" & vbLf & """" & Title & """", 48
  Else
    MsgBox "Well done!" & vbLf & Title, 64
  End If
End Sub


----------



## Excel_Phil

Hey ZVI, thanks for the quick reply. I wont work. I've tried it in two different computers... I really have no clue whats missing, I followed the steps, over and over. I do get the msgbox "IE window not found." I couldnt get it to work to get "Well Done". What kinda of bug can it be??  -  I appreciate a lot any help!!


----------



## ZVI

What is your Operating System,  version of Excel and version of IE?
Excel Home does not support CreateObject, for example.
 Hope you manually ran IE to the mentioned URL, not the another type of internet explorer like Opera. 

Not sure but there can be issue of IE protection settings (post#28).

Try Debugging VBA Code.
Use F8 for step by step evaluation, code should go into the lines  *If IsLike Then* and *If InStr(1,*... .
At debugging see what is in *w.LocationName* (type in *Immediate* window *?w.LocationName* and press *Enter*) - there should be something like is in *Title* variable


----------



## suresh_m

skybound7 said:


> Wanted to thank you for your post. It came in very helpful today.



Just wanted to know is it possible to input data from excel in a webpage and submit the buttion and return to excel for multipule times.

Thank you


----------



## mariod1049

ZVI said:


> Hi & Welcome to the Board!
> Try this:
> 
> 
> Rich (BB code):
> __
> 
> 
> 
> ' ZVI:2011-05-30 VBA Macro For Already Open IE Window
> ' Reference required: Tools - References - Microsoft Internet Controls
> Sub GetIE()
> 
> Dim shellWins As ShellWindows
> Dim IE As InternetExplorer
> 
> Set shellWins = New ShellWindows
> 
> If shellWins.Count > 0 Then
> ' Get IE
> Set IE = shellWins.Item(0)
> Else
> ' Create IE
> Set IE = New InternetExplorer
> IE.Visible = True
> End If
> 
> IE.Navigate "http://support.microsoft.com/kb/q176792/"
> 
> Set shellWins = Nothing
> Set IE = Nothing
> 
> End Sub
> 
> Regards,



I'm trying to convert this code to a function where I pass it two variables. However, the IE.Navigate line does not recognize the variables I pass to it. For example, passing partnum and cagecode variables like this does not work:   IE.Navigate "http://www.dlis.dla.mil/webflis/pub/pub_search.aspx?part=" & partnum & "&cage=" & cagecode" Can anyone tell me how this can be done?


----------



## ZVI

mariod1049 said:


> this does not work:   IE.Navigate "http://www.dlis.dla.mil/webflis/pub/pub_search.aspx?part=" & partnum & "&cage=" & cagecode


Hi,
1. Are you sure your question is about of Already Open IE Window? If not please start new thread.
2. What is the correct link in that example being typed manually?
Regards


----------



## mariod1049

ZVI said:


> Hi,
> 1. Are you sure your question is about of Already Open IE Window? If not please start new thread.
> 2. What is the correct link in that example being typed manually?
> Regards



I think this is the right thread. Since I will be using the function multiple times in one session, I want to keep using the same open IE window (and tab, if possible) rather than launching IE for each iteration. Here is how I revised the code. (For testing purposes, you can use partnumber = B2A and cagecode = 71744 and pass them as variables from a sub.) 





> Code:
> __
> 
> 
> ' ZVI:2011-05-30 VBA Macro For Already Open IE Window
> ' Reference required: Tools - References - Microsoft Internet Controls
> Function GetIE(partnum As String, cagecode As String)
> 
> Dim shellWins As ShellWindows
> Dim IE As InternetExplorer
> 
> Set shellWins = New ShellWindows
> If shellWins.Count > 0 Then
> ' Get IE
> Set IE = shellWins.Item(0)
> Else
> ' Create IE
> Set IE = New InternetExplorer
> IE.Visible = True
> End If
> IE.Navigate "http://www.dlis.dla.mil/webflis/pub/pub_search.aspx?part=" & partnum & "&cage=" & cagecode"
> Set IE = Nothing
> Set shellWins = Nothing
> End Function


----------



## ZVI

Well, I see your revising of the code is good!

Just delete an extra double quotes symbol at the end of the code line with IE.Navigate
was: IE.Navigate "http://www.dlis.dla.mil/webflis/pub/pub_search.aspx?part=" & partnum & "&cage=" & cagecode*"*
should be: IE.Navigate "http://www.dlis.dla.mil/webflis/pub/pub_search.aspx?part=" & partnum & "&cage=" & cagecode
Then it works:


		Rich (BB code):
__


Sub Test()
  GetIE "B2A", "71744"
End Sub


 And welcome to the MrExcel!


----------



## mariod1049

I found my own error! I had an extra quote at the end of the URL that shouldn't have been there. Thank you anyway, Mr. Excel!


mariod1049 said:


> I think this is the right thread. Since I will be using the function multiple times in one session, I want to keep using the same open IE window (and tab, if possible) rather than launching IE for each iteration. Here is how I revised the code. (For testing purposes, you can use partnumber = B2A and cagecode = 71744 and pass them as variables from a sub.)


----------



## RL101

Hi all,

I'm looking to create a VBA macro which will be ran from Excel (2003 or 2010) & which works with Internet Explorer. I have added 'Microsoft Internet Controls' to VBA References, and have looked at plenty of VBA code on the forum which opens & then navigates to specific websites. 

However, what I need is for this macro to affect an already open IE window.

Does anyone have an idea of the syntax / command to have excel "select" a specific IE window already open? 

Many thanks!


----------



## rwhitmore90

ZVI said:


> Hi Phil, welcome to MrExcel!
> 
> Well, lets's test the finding of IE window by its title.
> 
> Do as follows:
> 
> 1. Select and copy all the below code to the clipboard.
> 2. In *VBE* use menu *Insert* - *Module* to create *Module1*
> 3. Paste from the clipboard the code of the function *GetIeByTitle* to that module
> 4. Open IE on this page  http://www.mrexcel.com/forum/excel-...pplications-macro-already-open-ie-window.html
> 5. Run the *Test_GetIeByTitle* - the IE window have to be found. Message will inform about success.
> 6. Close that IE window and run again *Test_GetIeByTitle* - IE window shall not be found, error message will appear.
> 
> 
> 
> 
> Rich (BB code):
> __
> 
> 
> ' ZVI:2013-09-10 Get IE object of already open window by its title
> ' Arguments:
> '   Title     -  title of the searchied IE window
> '   [IsLike]  -  False/True = exact/partial searching, default is False
> '   [IsFocus] -  False/True = don't_activate/activate IE window, default is False
> Function GetIeByTitle(Title, Optional IsLike As Boolean, Optional IsFocus As Boolean) As Object
> Dim w As Object
> For Each w In CreateObject("Shell.Application").Windows
> With w
> If .Name = "Windows Internet Explorer" Then
> If IsLike Then
> If InStr(1, .LocationName, Title, vbTextCompare) > 0 Then   ' ZVI:2013-09-10 fixed
> ' Partial title of window is found - activate IE window
> If IsFocus Then
> w.Visible = False
> w.Visible = True
> End If
> Set GetIeByTitle = w
> Exit For
> End If
> Else
> If StrComp(.LocationName & " - " & .Name, Title, 1) = 0 Then  ' ZVI:2013-09-10 fixed
> ' Title of window is found - activate IE window
> If IsFocus Then
> w.Visible = False
> w.Visible = True
> End If
> Set GetIeByTitle = w
> Exit For
> End If
> End If
> End If
> End With
> Next
> Set w = Nothing
> End Function
> 
> ' Testing subroutine for the above function GetIeByTitle.
> '
> ' 1. Try this macro with already open IE window on this page:
> '    http://www.mrexcel.com/forum/excel-questions/553580-visual-basic-applications-macro-already-open-ie-window.html
> '    Macro should successfuly find the IE window by its Title.
> '
> ' 2. Close that IE window and try the code again - IE window will not be found.
> '    Error message will appear.
> '
> Sub Test_GetIeByTitle()
> Dim IE As Object
> Dim Title As String
> Title = "VBA Macro For Already Open IE Window"
> Set IE = GetIeByTitle(Title, True, True)
> If IE Is Nothing Then
> MsgBox "IE window with this Title is not found:" & vbLf & """" & Title & """", 48
> Else
> MsgBox "Well done!" & vbLf & Title, 64
> End If
> End Sub



ZVI, I'm not sure you are still checking this thread but I have a few questions for you. I got this to work very well to check whether the title of the document matches. I have a question:

1) Can I get this to work declaring Dim IE as InternetExplorer? This will be in the sub I build. The reason I need this code to get the active IE session is because the URL to the internal web application that I'm trying to automate never changes. It is a series of javascript functions that eventually get to a form I am trying to automate. Unfortunately for me, the id tags of the web page also change. 

I really appreciate your help. This thread and some of your other posts have been extremely helpful.


----------



## ZVI

Hi rwhitmore90,

Glad the code of this thread is helpful for you.

To declare *Dim IE As InternetExplorer* the reference to *Microsoft Internet Controls* is required in *VBE-Tools-References*. 
It is so called early binding.

Your code then may look like this:


		Rich (BB code):
__


Sub Test_GetIeByTitle()
  Dim IE As *InternetExplorer*
  Dim Title As String
  Title = "VBA Macro For Already Open IE Window"
  Set IE = GetIeByTitle(Title, True, True)
  If IE Is Nothing Then
    MsgBox "IE window with this Title is not found:" & vbLf & """" & Title & """", 48
  Else
    MsgBox "Well done!" & vbLf & Title, 64
  End If
End Sub

 
Best Regards


----------



## bryanliang

Hi ZVI,
 May I know how to use the getelementbyid after the macro was  active the web page which ady open?I would like to fill up the form in that webpage.tq..


----------



## ZVI

bryanliang said:


> Hi ZVI,
> May I know how to use the getelementbyid after the macro was  active the web page which ady open?


Has not seen this message earlier...
But better late than never 

Getting of IE.Document.GetElementById is as usual.
For example, open this web page in IE and try this code:


		Rich (BB code):
__


Sub Test_GetIeByTitle()
  Dim IE As Object, x
  Dim Title As String
  Title = "VBA Macro For Already Open IE Window"
  Set IE = GetIeByTitle(Title, True, True)
  If IE Is Nothing Then
    MsgBox "IE window with this Title is not found:" & vbLf & """" & Title & """", 48
  Else
    MsgBox *IE.Document.GetElementById("pagetitle").InnerTex*t, , "pagetitle"
    'MsgBox "Well done!" & vbLf & Title, 64
  End If
End Sub


----------



## sugaprasad

Hi ZVI,

I am trying to replace the existing URL in the address bar of already opened IE window. So far this is my code.




		Code:
__


Sub Replace_URL()

  Dim shellWins As ShellWindows
  Dim ie As InternetExplorer


  Set shellWins = New ShellWindows


  If shellWins.Count > 0 Then
    ' Get IE
    Set ie = shellWins.Item(0)
  Else
    ' Create IE
    Set ie = New InternetExplorer
    ie.Visible = True
  End If


   
  ie.navigate "javascript: $find('ReportViewerControl').exportReport('EXCEL');"








  Set shellWins = Nothing
  Set ie = Nothing


End Sub

Here its goes in to else part. But the navigate link is opening in a new tab. but i want this to replace the url in existing tab.
Is this can be done. Please help me.


----------



## jackson89

Need some help!!!! i've been trying to code a macro using twebst. But the problem with twebst is that it doesn't write a code when a link is clicked that open the webpage in a new window. Now how do i navigate my code which as been written for the login page to a new page. I want to download the data from the new page unto a excel sheet. Below is the code that was generated.
Sub OpenTwebstMacro()
    Dim core As ICore
    Set core = New OpenTwebstLib.core

    Dim browser As IBrowser
    Set browser = core.StartBrowser("http:xxxxx/login.aspx")

    Call browser.FindElement("input text", "id=UserName").InputText("xxxx")
    Call browser.FindElement("input password", "id=Password").InputText("xxxx")
    Call browser.FindElement("input submit", "id=LoginButton").Click
    Call browser.FindElement("a", "id=ctl00_TreeView1t5").Click
    Call browser.FindElement("select", "id=ctl00_ContentPlaceHolder1_ddlAccyear").Select("2014-2015")
    Call browser.FindElement("input submit", "id=ctl00_ContentPlaceHolder1_btnCurrentEnrollment").Click ' here the new window opens up
' I want to navigate to the new webpage that has been opened start extracting my required data

Sheets("Run").Select


End Sub


----------



## Mepwnz2010

This thread is pretty awesome. Thank you for the help ZVI, but now I have my own question. I of course am new to VBA. I've taken the script from thread and formed it with another script to check if all cells have been filled out by the user. Next I need to click a button and ultimately I will need to fill in some boxes, drop boxes, and of course click more boxes. I literally started messing with VBA only a week ago so I'm stuck. If I could just get past clicking this first button I know I could figure out the rest. I cant provide a link to the button I need to click cause its for work, but I will paste the script for the button and my macro script. Thanks in advance if I get any help, and if I don't thanks anyways just for this thread.

---------------------------------------------My macro------------------------------------------------------


		Code:
__


' Arguments:
'  Title    -  title of the searchied IE window
'  [IsLike]  -  False/True = exact/partial searching, default is False
'  [IsFocus] -  False/True = don't_activate/activate IE window, default is False
Function GetIeByTitle(Title, Optional IsLike As Boolean, Optional IsFocus As Boolean) As Object
  Dim w As Object
  For Each w In CreateObject("Shell.Application").Windows
    With w
      If .Name = "Windows Internet Explorer" Then
        If IsLike Then
          If InStr(1, .LocationName, Title, vbTextCompare) > 0 Then  ' ZVI:2013-09-10 fixed
            ' Partial title of window is found - activate IE window
            If IsFocus Then
              w.Visible = False
              w.Visible = True
            End If
            Set GetIeByTitle = w
            Exit For
          End If
        Else
          If StrComp(.LocationName & " - " & .Name, Title, 1) = 0 Then  ' ZVI:2013-09-10 fixed
            ' Title of window is found - activate IE window
            If IsFocus Then
              w.Visible = False
              w.Visible = True
            End If
            Set GetIeByTitle = w
            Exit For
          End If
        End If
      End If
    End With
  Next
  Set w = Nothing
 
      
End Function
                         '---------everything above here sets up rules for the macro---------------------

Sub CreateSFcase()
If IsEmpty(Range("a1")) Then
   MsgBox "No. of Bookings is blank" & """", 48
   Stop
End If

If IsEmpty(Range("a2")) Then
   MsgBox "Dispute Amount is blank" & """", 48
   Stop
End If

If IsEmpty(Range("a3")) Then
   MsgBox "Transaction Post Date is blank" & """", 48
   Stop
End If

If IsEmpty(Range("a4")) Then
   MsgBox "Accounting Assigned To is blank" & """", 48
Stop
End If

If IsEmpty(Range("a5")) Then
   MsgBox "Contact/Account Lookup Results is blank" & """", 48
   Stop
End If

If IsEmpty(Range("a6")) Then
   MsgBox "Contact/Account Lookup Results is blank" & """", 48
   Stop
End If

If IsEmpty(Range("a7")) Then
   MsgBox "Additional To is blank" & """", 48
   Stop
End If

'-------------------------------------Everything from to the above green line checks to make sure macro is completely filled out before running the marco---------------------------------------------------------


  Dim IE As Object
  Dim Title As String
  Title = "New Case: Select Case Record Type ~ Salesforce.com - Unlimited Edition"
  Set IE = GetIeByTitle(Title, True, True)
  If IE Is Nothing Then
    MsgBox "Please open the correct Salesforce window" & vbLf & """" & Title & """", 48
    Stop
     End If
'---------------------------------this pulls up SF---------------------------------------------


End Sub


------------------------------------And heres the button---------------------------------------



		Code:
__


'<td class="pbTitle">...</td>                 'this looks like its just the bar the botton is on'<td class="pbButtonb" id="bottomButtonRow">  'this looks like its just the bar the botton is on
  '<input value="Continue" class="btn" title="Continue" name="save" type="submit">   'this is the botton


----------



## ZVI

sugaprasad said:


> But the navigate link is opening in a new tab. but i want this to replace the url in existing tab.
> Is this can be done


As a workaround - read new URL, close the created extra tab and navigate old tab to that URL.


----------



## ZVI

jackson89 said:


> i've been trying to code a macro using twebst.


Have no Twebst framework installed on my PC. Try asking Twebst Support


----------



## ZVI

Mepwnz2010 said:


> If I could just get past clicking this first button I know I could figure out the rest.


Clicking button on web page is a bit out of the scope of this thread - better to create the new thread for this. 
Commonly code of each web page is almost unique - there are no strict rules for the parsing.
Sometimes code for clicking button on web-page can look like these (depends on HTML code of web site): 
IE.Document.GetElementsById("bottomButtonRow").Item(0).InvokeMember("submit")
or
IE.Document.Forms.GetElementsByName("save").Item(0).InvokeMember("submit")
or
IE.Document.GetElementsByName("save").Item(0).Click
or
IE.Document.GetElementsById("bottomButtonRow").Item(0).Click
...


----------



## RL101

Hi all,

I'm looking to create a VBA macro which will be ran from Excel (2003 or 2010) & which works with Internet Explorer. I have added 'Microsoft Internet Controls' to VBA References, and have looked at plenty of VBA code on the forum which opens & then navigates to specific websites. 

However, what I need is for this macro to affect an already open IE window.

Does anyone have an idea of the syntax / command to have excel "select" a specific IE window already open? 

Many thanks!


----------



## sevape

Hi,

Just wanted to exress my gratitud towards this post, been searchingh and testin various ways but nothing worked until I stumbled across this... Thank You!


----------



## ZVI

sevape said:


> Hi,
> 
> Just wanted to exress my gratitud towards this post, been searchingh and testin various ways but nothing worked until I stumbled across this... Thank You!


My pleasure, sevape! 
Welcome to the MrExcel Board!


----------



## hselvik

Hi. I need some help writing a VBA-code for a command-button in an Excel-sheet I am working on, and figured I could try this forum. I am not sure if this action is possible, but I am hoping for a code that opens a web-page, adds information from the Excel-sheet into a search-field on this web-page, and performs this search. Is this possible?


----------



## Mepwnz2010

ZVI said:


> Clicking button on web page is a bit out of the scope of this thread - better to create the new thread for this.
> Commonly code of each web page is almost unique - there are no strict rules for the parsing.
> Sometimes code for clicking button on web-page can look like these (depends on HTML code of web site):
> IE.Document.GetElementsById("bottomButtonRow").Item(0).InvokeMember("submit")
> or
> IE.Document.Forms.GetElementsByName("save").Item(0).InvokeMember("submit")
> or
> IE.Document.GetElementsByName("save").Item(0).Click
> or
> IE.Document.GetElementsById("bottomButtonRow").Item(0).Click
> ...


Hey ZVI this reply was awesome, and this thread in general took me down the path I needed to learn a lot. So thank you... You the man! Got another question for you now. Do you think the get IE by title code could be made to work with google chrome?


----------



## ZVI

Open in Excel all linked workbooks and save each workbook via 'File - Save As' onto required folder. 
After that delete old copies of workbooks from their previous folders.


----------



## ZVI

ZVI said:


> Open in Excel all linked workbooks and save each workbook via 'File - Save As' onto required folder.
> After that delete old copies of workbooks from their previous folders.


Wrong posting - I'm apologising, it was for another thread.



Mepwnz2010 said:


> Do you think the get IE by title code could be made to work with google chrome?


I am not using Google Chrome. 
 Surely the handling of window by its title in VBA is possible with involving of API-code.
But in VBA you can't get Google Chrome object similar to IE with its methods & properties.


----------



## Pegaso

ZVI,


Thanks for your help in answering all of those questions regarding the subject of controlling already existing IE windows.


I'm building a more complex code, but in a nutshell, what I need is to get the HTML code of the page referred in the code, copy and save it as a .txt file, this is what I have:




		Code:
__


'Creates the links to access the files in each vault
'Opens each external link, creates a list with all the files and local links for each one


Sub Main()


Dim i As Integer
Dim s As Integer
Dim t As Integer
Dim VaultMin As Integer
Dim VaultMax As Integer
Dim NumRec As Integer
Dim NumTot As Integer
Dim Path As String
Dim PathName As String
Dim fs As Object
Dim IE As Object
Dim objDoc As Object
Dim NPOFile$, myFile$
Dim f As Object
Dim WB1 As Workbook
Dim WB2 As Workbook


Sheets("Summary").Activate
Set WB1 = ThisWorkbook
VaultMin = Cells(2, 2)
VaultMax = Cells(2, 4)


For t = VaultMin To VaultMax
    
    'Section 1 of 3: Create vault URL, open, grab HTML code
    
    Cells(2, 5) = t
    VaultURL = Cells(2, 6)
    VaultPath = Cells(3, 6)
    VaultName = "HTML-" & t & ".txt"
    
    Set fs = CreateObject("Scripting.FileSystemObject") 'This creates the .txt to store the webpage code of the page to open
    Set a = fs.CreateTextFile(VaultPath & VaultName, True)
    a.Close
    
    'ZVI's code starts here!
  
    With CreateObject("Shell.Application").Windows
    
        If .Count > 0 Then
          ' Get IE
          Set IE = .Item(0) ' or .Item(.Count - 1)
        Else
          ' Create IE
          Set IE = CreateObject("InternetExplorer.Application")
          IE.Visible = True
        End If
  
    End With
    
    Range(Cells(2, 6), Cells(2, 6)).Select 'This is where the hyperlink resides in the excel sheet
    Selection.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
    
    'Wait for page to load!
    
    Do
    If IE.ReadyState = 4 Then
    IE.Visible = True
    Exit Do
    Else


    DoEvents
    End If
    Loop


    Set objDoc = IE.Document
    strMyPage = IE.body.innerHTML 'This line gives error code 438, "Object doesn't support this property or method
    strMyPage = IE.innerHTML
    
    NPOFile = "NotePad.exe " & myFile


    'Work with file [Append Text to File].
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.OpenTextFile(VaultPath & VaultName, 8, TristateUseDefault)


    f.Write Chr(9) & strMyPage
    f.Close
    
Next t


End Sub


I'm getting an error here:



		Code:
__


strMyPage = IE.body.innerHTML 'This line gives error code 438, "Object doesn't support this property or method


Thanks in advance for your help.

Rgds!

Pegaso


----------



## ZVI

Hi Pegaso,

The problem is at least here: strMyPage = IE.body.innerHTML
becuase Body is a child of Document but not of IE object directly.
Use this: strMyPage = IE.*Document*.Body.innerHTML

To simplify your task try using the shown below function GetBodyInnerHTML.
It returns  innerHTML of the web page referenced in hyperlink of the passed cell.
Put its code to the module where your Main subroutine resides and then just call it from your code like this:


		Rich (BB code):
__


Sub Main()
 
  ' ... Your code
 
  ' ZVI's code starts here! (the single line now)
   strMyPage = GetBodyInnerHTML(Range("F2"))
 
  ' Work with file [Append Text to File]
  ' ... Your code
 
End Sub

 


		Rich (BB code):
__


Sub Test()
  Dim strMyPage As String
  ' Put Body's nnerHTML to the strMyPage variable
  strMyPage = GetBodyInnerHTML(Range("F3"))
  ' Print strMyPage into Immediate window of VBE
  Debug.Print strMyPage
End Sub
 
Function GetBodyInnerHTML(Cell As Range, Optional WaitSeconds As Long = 10) As String
' ZVI:2015-04-20 Returns InnerHTML of the web page referenced in the hyperlink of the Cell
' (already open IE window is used if exists)
' Arguments:
'   Cell        - the cell with hyperlink to the web page
'   WaitSeconds - (optional) timeout in seconds for IE navigation
  Dim IE As Object
  Dim t As Single
  Dim Url As String
  With CreateObject("Shell.Application").Windows
    If .Count > 0 Then
      ' Get IE
      Set IE = .Item(0)  ' or .Item(.Count - 1)
    Else
      ' Create IE
      Set IE = CreateObject("InternetExplorer.Application")
      IE.Visible = True
    End If
  End With
  ' Get url from the cell
  If Cell.Hyperlinks.Count > 0 Then
    ' Hyperlink object is present in the cell
    Url = Cell.Hyperlinks(1).Address
  Else
    ' May be hyperlink is in the cell's value (text)
    Url = Cell.Value
  End If
  ' Do navigation
  IE.Navigate Url
  ' Charge the timeout
  t = Timer + WaitSeconds
  ' Wait for "IE is ready" state
  While IE.ReadyState <> 4 And Timer < t: DoEvents: Wend
  ' Wait for "IE.Document is completely downloaded" state
  If Timer < t Then
    While IE.Document Is Nothing And Timer < t: DoEvents: Wend
  Else
    Err.Raise vbObjectError + 513, , "Timeout happens: " & WaitSeconds & " seconds"
  End If
  ' Return Body's innerHTML
  GetBodyInnerHTML = IE.Document.Body.innerHTML
  ' Clear the memory of object variable
  Set IE = Nothing
End Function

 
Regards


----------



## Pegaso

ZVI,


Thanks for your quick answer.




> ZVI said:
> 
> 
> 
> Hi Pegaso,
> 
> 
> The problem is at least here: strMyPage = IE.body.innerHTML
> becuase Body is a child of Document but not of IE object directly.
> Use this: strMyPage = IE.Document.Body.innerHTML
> 
> 
> 
> 
> 
> Click to expand...
> 
> 
> 
> I replaced strMyPage = IE.body.innerHTML with strMyPage = IE.Document.Body.innerHTML, but it didn't work, "Error 483, Object doesn't support property or method". That didn't surprise me since you mentioned that there could be other errors around,
> 
> 
> Then I used your suggestion using GetBodyInnerHTML, but unfortunately the error persists, the line:
> 
> 
> 
> 
> 
> 
> 
> 
> GetBodyInnerHTML = IE.Document.Body.innerHTML
> 
> Click to expand...
> 
> 
> 
> Click to expand...
> 
> 
> Gives me the same error
> 
> 
> Any ideas?
> 
> 
> Again, thanks for your help!
> 
> 
> Pegaso
Click to expand...


----------



## ZVI

Well, then please copy all the below updated code into VBA module and run Test1 subroutine.
If it works then try new GetBodyInnerHTML with your workbook.
 If it does not work then what will happen if you click hyperlink of F2 cell in testing sheet which is created by Test1 subroutine?


		Rich (BB code):
__


Sub Test1()
  Dim strMyPage As String
  ' Create new worbook for testing
  With Workbooks.Add
    With Sheets(1)
      ' Prepare testing sheet
      .Activate
      .Name = "Summary"
      ' Add hyperlink for the testing
      .Hyperlinks.Add Anchor:=.Range("F2"), _
                      Address:="http://www.mrexcel.com/forum/faq.php", _
                      ScreenTip:="MrExcel Message Board FAQ", _
                      TextToDisplay:="MrExcel FAQ"
    End With
  End With
  ' Put Body's innerHTML to the strMyPage variable
  strMyPage = GetBodyInnerHTML(Range("F2"))
  ' Print strMyPage into Immediate window of VBE
  Debug.Print strMyPage
End Sub
 
 
Function GetBodyInnerHTML(Cell As Range, Optional WaitSeconds As Long = 10) As String
  ' ZVI:2015-04-20 http://www.mrexcel.com/forum/excel-questions/553580-visual-basic-applications-macro-already-open-ie-window-2.html
  ' Arguments:
  '   Cell        - the cell with hyperlink to the web page
  '   WaitSeconds - (optional) timeout in seconds for IE navigation
  ' Returns InnerHTML of the web page referenced in the hyperlink of the Cell
  ' (already open IE window is used if exists)
  Dim IE As Object, w As Object
  Dim t As Single
  Dim Url As String
  For Each w In CreateObject("Shell.Application").Windows
    If w.Name = "Windows Internet Explorer" Then
      ' Get IE
      'Debug.Print "IE is already open" ' <-- for testing
      Set IE = w
      Exit For
    End If
  Next
  If IE Is Nothing Then
    ' Create IE
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Silent = True
    IE.Visible = True
    'Debug.Print "New IE" ' <-- for testing
  End If
  ' Get url from the cell
  If Cell.Hyperlinks.Count > 0 Then
    ' Hyperlink object is present in the cell
    Url = Cell.Hyperlinks(1).Address
  Else
    ' May be hyperlink is in the cell's value (text)
    Url = Cell.Value
  End If
  ' Do navigation
  IE.Navigate Url
  ' Charge the timeout
  t = Timer + WaitSeconds
  ' Wait for "IE is ready" state
  While IE.ReadyState <> 4 And Timer < t: DoEvents: Wend
  ' Wait for "IE.Document is completely downloaded" state
  If Timer < t Then
    While IE.Document Is Nothing And Timer < t: DoEvents: Wend
  Else
    Err.Raise vbObjectError + 513, , "Timeout happens: " & WaitSeconds & " seconds"
  End If
  ' Return Body's innerHTML
  GetBodyInnerHTML = IE.Document.Body.innerHTML
  ' Clean the memory of object variables
  Set w = Nothing
  Set IE = Nothing
End Function


----------



## RL101

Hi all,

I'm looking to create a VBA macro which will be ran from Excel (2003 or 2010) & which works with Internet Explorer. I have added 'Microsoft Internet Controls' to VBA References, and have looked at plenty of VBA code on the forum which opens & then navigates to specific websites. 

However, what I need is for this macro to affect an already open IE window.

Does anyone have an idea of the syntax / command to have excel "select" a specific IE window already open? 

Many thanks!


----------



## Pegaso

ZVI,

It does work! I just quickly tested but I was able to see the code in the immediate window, I'll incorporate it to the rest of the code and do a full test.

Something else, how can I close each new instance of IE at the end of the procedure? (I need to run this over a large number of websites, and it doesn't make any sense to leave them open once the program is done with each one of them.

I tried IE.Close, IE.Quit but no success, I checked the subject and I couldn't find something useful.

Warmest regards ZVI!

Pegaso


----------



## ZVI

Thanks for the fast testing and the feedback!
To quit created instance of IE use the flag (boolean) variable and do IE.Quit before Set IE = Nothing , like this:


		Rich (BB code):
__


Function GetBodyInnerHTML(Cell As Range, Optional WaitSeconds As Long = 20) As String
  ' ZVI:2015-04-21 http://www.mrexcel.com/forum/excel-questions/553580-visual-basic-applications-macro-already-open-ie-window-2.html
  ' Arguments:
  '   Cell        - the cell with hyperlink to the web page:
  '   WaitSeconds - (optional) timeout in seconds for IE navigation
  ' Returns InnerHTML of the web page referenced in the hyperlink of the Cell
  ' (already open IE window is used if exists)
  Dim IE As Object
  Dim t As Single
  Dim Url As String
  Dim IsNew As Boolean
  For Each IE In CreateObject("Shell.Application").Windows
    If IE.Name = "Windows Internet Explorer" Then
      ' IE window found
      'Debug.Print "IE is already open" ' <-- For testing
      Exit For
    End If
  Next
  If IE Is Nothing Then
    ' Create new IE object
    IsNew = True
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Silent = True
    IE.Visible = True     ' <-- Comment it to skip blinking
    'Debug.Print "New IE" ' <-- For testing
  End If
  ' Get url from the cell
  If Cell.Hyperlinks.Count > 0 Then
    ' Hyperlink object is present in the cell
    Url = Cell.Hyperlinks(1).Address
  Else
    ' May be hyperlink is in the cell's value (text)
    Url = Cell.Value
  End If
  ' Do navigation
  IE.Navigate Url
  ' Charge the timeout
  t = Timer + WaitSeconds
  ' Wait for "IE is ready" state
  While IE.ReadyState <> 4 And Timer < t: DoEvents: Wend
  ' Wait for "IE.Document is completely downloaded" state
  If Timer < t Then
    While IE.Document Is Nothing And Timer < t: DoEvents: Wend
  Else
    Err.Raise vbObjectError + 513, , "Timeout happens: " & WaitSeconds & " seconds"
  End If
  ' Return Body's innerHTML
  GetBodyInnerHTML = IE.Document.Body.innerHTML
  ' Quit IE
  If IsNew Then IE.Quit
  ' Clear the memory of object variable
  Set IE = Nothing
End Function


----------



## mynameissaturn

Hi ZVI,

May you help me as well? I hope I am on the right thread.

This time I am using Firefox (with installed Selenium) with already opened Website titled "All Incoming Work Requests". I also have Activity ID's on excel column A and Employee numbers on excel column B.

Column A        Column B
1-14VOW19    ACAB3024
1-14VPK3E     ACAB3007
1-14VPJP9     ACAB3008
1-14VR0NX    ACATB3017
1-14VP388     ACATB3013


What I want to do is,

1. Click the Query button (button id="s_1_1_21_0_Ctrl") on the website. 
(Then wait for the site to be completely loaded. Approx 1-2 seconds to load)
2. Copy the 1st Activity ID on excel Column A.
3. Select the Activity ID field (input id="1_Activity_Id") and paste the Activity ID that was copied.
4. Copy the 1st Employee number on excel Column B.
5. Select the Owner field (input id="1_Owned_By") and paste the Employee number that was copied.
6. Then click on the GO button (button id="s_1_1_20_0_Ctrl") so that the Activity ID will be assigned to the employee.
(Then wait for the site to be completely loaded. Approx 1-2 seconds to load)
7. Again back to step number 1 and loop this process until all the data on column A and column B are done.

This will be use for Dispatching Works automatically. This process consumes so much time and effort on manually assigning more than a hundred of Activity IDs daily.

Hoping to here from you.

Thanks a lot!


----------



## Pegaso

Vladimir,

After a few modifications to handle the enormous amount of files, I was able to download ~100k .pdf files, thanks a lot for your help, I improved my knowledge in the use of excel-vba to control other software as IE in this case.

Now I'm facing a similar challenge, but this time I need to deal with the non-pdf files in my database. The .pdf files are downloaded automatically (I had to change options in Adobe Acrobat to disable the .pdf support to IE), the rest of the files, I found no way to force IE to download them, (.txt, .doc, .jpg, .bmp, etc..). I found an alternative using HTML5 (see here), I was able to create .html files that when open, only display a link, when the link is clicked, the file starts to download. This is an improvement but since I'm not familiar with HTML5 I need help in making the code to do the following:

1. Automatically click the link, so it will trigger the downloading of the file
2. If possible, give a name to the file to download file, it is simply saved as ParseFile.htm, since I need to do this several thousand times, I would like the file to have a meaningful name.

The following code creates the .html file with the required link and opens the file later on, but I still need to click the link and if possible give a meaningful name to the file, preferably before downloading it.



		Code:
__


[/FONT][/COLOR]#If VBA7 Then    Private Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
        (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
#Else
    Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
        (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
#End If


Sub CreateHTML()


Sheets("Summary-1").Activate


VaultMin = Cells(2, 2)
VaultMax = Cells(3, 2)
FilePath = Cells(2, 5)


TextA = """"
Text1 = "<a href="
Text2 = "http://xx.yyyzzz.com/new_zzzggghhhASP/fileParse.php?attachID="
Text4 = "&fileID="
Text6 = " download="
Text7 = "FileName"
Text8 = ">File abc</a>"


For t = VaultMin To VaultMax
    Text = ""
    If Cells(t, 5) <> ".pdf" Then
    
        Text3 = Cells(t, 6)
        Text5 = Cells(t, 7)
        Filename = "HTML-" & Text3 & "-" & Text5 & ".html"
        MyFile = FilePath & Filename
        Text = Text1 & TextA & Text2 & Text3 & Text4 & Text5 & TextA & Text6 & TextA & Text7 & TextA & Text8
        
        Set fs = CreateObject("Scripting.FileSystemObject")
        Set f = fs.CreateTextFile(MyFile, True)
    
        f.Write Chr(9) & Text 'strMyPage
        f.Close
        
        Call OpenAnyFile(MyFile)
        
    Else: End If


Next t


End Sub


Function OpenAnyFile(FileToOpen As String)
     
    Call ShellExecute(0, "Open", FileToOpen & vbNullString, _
    vbNullString, vbNullString, 1)
     
End Function


[COLOR=#000000][FONT=verdana]


By the way, this HTML5 script doesn't work in IE, just in Chrome, so I have the additional problem of controlling Chrome with VBA (with IE is well documented, but I couldn't find the same level of documentation for Chrome)

Apologies if this is not placed exactly in the right place, but since the tread started here I prefer to keep the updates in the same place

Warmest regards and thanks in advance Vladimir for all your help!

Pegaso


----------



## tintino

Pegaso said:


> Vladimir,
> 
> After a few modifications to handle the enormous amount of files, I was able to download ~100k .pdf files, thanks a lot for your help, I improved my knowledge in the use of excel-vba to control other software as IE in this case.
> 
> Now I'm facing a similar challenge, but this time I need to deal with the non-pdf files in my database. The .pdf files are downloaded automatically (I had to change options in Adobe Acrobat to disable the .pdf support to IE), the rest of the files, I found no way to force IE to download them, (.txt, .doc, .jpg, .bmp, etc..). I found an alternative using HTML5 (see here), I was able to create .html files that when open, only display a link, when the link is clicked, the file starts to download. This is an improvement but since I'm not familiar with HTML5 I need help in making the code to do the following:
> 
> 1. Automatically click the link, so it will trigger the downloading of the file
> 2. If possible, give a name to the file to download file, it is simply saved as ParseFile.htm, since I need to do this several thousand times, I would like the file to have a meaningful name.
> 
> The following code creates the .html file with the required link and opens the file later on, but I still need to click the link and if possible give a meaningful name to the file, preferably before downloading it.
> 
> 
> 
> 
> Code:
> __
> 
> 
> #If VBA7 Then    Private Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
> (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
> #Else
> Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
> (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
> #End If
> 
> 
> Sub CreateHTML()
> 
> 
> Sheets("Summary-1").Activate
> 
> 
> VaultMin = Cells(2, 2)
> VaultMax = Cells(3, 2)
> FilePath = Cells(2, 5)
> 
> 
> TextA = """"
> Text1 = "<a href="<br /> Text2 = " http:="" xx.yyyzzz.com="" new_zzzggghhhasp="" fileparse.php?attachid="
> Text4 = " &fileid="
> Text6 = " download="
> Text7 = " filename"
> Text8 = ">File abc"
> 
> 
> For t = VaultMin To VaultMax
> Text = ""
> If Cells(t, 5) <> ".pdf" Then
> 
> Text3 = Cells(t, 6)
> Text5 = Cells(t, 7)
> Filename = "HTML-" & Text3 & "-" & Text5 & ".html"
> MyFile = FilePath & Filename
> Text = Text1 & TextA & Text2 & Text3 & Text4 & Text5 & TextA & Text6 & TextA & Text7 & TextA & Text8
> 
> Set fs = CreateObject("Scripting.FileSystemObject")
> Set f = fs.CreateTextFile(MyFile, True)
> 
> f.Write Chr(9) & Text 'strMyPage
> f.Close
> 
> Call OpenAnyFile(MyFile)
> 
> Else: End If
> 
> 
> Next t
> 
> 
> End Sub
> 
> 
> Function OpenAnyFile(FileToOpen As String)
> 
> Call ShellExecute(0, "Open", FileToOpen & vbNullString, _
> vbNullString, vbNullString, 1)
> 
> End Function
> 
> 
> 
> By the way, this HTML5 script doesn't work in IE, just in Chrome, so I have the additional problem of controlling Chrome with VBA (with IE is well documented, but I couldn't find the same level of documentation for Chrome)
> 
> Apologies if this is not placed exactly in the right place, but since the tread started here I prefer to keep the updates in the same place
> 
> Warmest regards and thanks in advance Vladimir for all your help!
> 
> Pegaso




@Pegaso, this is off-topic, but there are many ways to download a file  (google VBA download file) 

For example you can use  XMLHTTP  object

This function saves the file found at url, to the path passed in parameter spath  (spath is a complete path with file name)
It returns false, if it failed...  and it considers any http status code other than  200, as a fail.




		Code:
__


Function http_FetchFile(sURL As String, sPath) As Boolean

 Dim oXHTTP As Object
 Dim oStream As Object
Dim success As Boolean


    Set oXHTTP = CreateObject("MSXML2.XMLHTTP")
    Set oStream = CreateObject("ADODB.Stream")
    Application.StatusBar = "Fetching " & sURL & " as " & sPath
    oXHTTP.Open "GET", sURL, False
    oXHTTP.send
    Debug.Print oXHTTP.Status
    With oStream
        .Type = 1 'adTypeBinary
        .Open
        .Write oXHTTP.responseBody
        If oXHTTP.Status = 200 Then
            .SaveToFile sPath, 2 'adSaveCreateOverWrite
            success = True
        Else
            success = False
        End If
        .Close
    End With
    Set oXHTTP = Nothing
    Set oStream = Nothing
    Application.StatusBar = False

http_FetchFile = success


End Function


----------



## Kurt

Hello ZVI,

Lot's of great examples here. I found Nories old thread and your old thread while doing a search.

Can you take a look at this post I continued please?

Thanks,

Kurt


----------



## Wolfee200

I just wanted to say Thank you for the good explanations in this thread.  I am having to do a work around as work install O365 for email and now my IE scripts for Excel are failing.  This has helped me re-link to IE.


----------



## Kurt

Wolfee200 said:


> I just wanted to say Thank you for the good explanations in this thread.  I am having to do a work around as work install O365 for email and now my IE scripts for Excel are failing.  This has helped me re-link to IE.



I am glad this thread was able to help you out.

Have you done anything similar in Excel using VBA and if so do you mind sharing your code?

Have a great rest of the week!


----------



## Kurt

ZVI said:


> Well, then please copy all the below updated code into VBA module and run Test1 subroutine.
> If it works then try new GetBodyInnerHTML with your workbook.
> If it does not work then what will happen if you click hyperlink of F2 cell in testing sheet which is created by Test1 subroutine?
> 
> 
> Rich (BB code):
> __
> 
> 
> Sub Test1()
> Dim strMyPage As String
> ' Create new worbook for testing
> With Workbooks.Add
> With Sheets(1)
> ' Prepare testing sheet
> .Activate
> .Name = "Summary"
> ' Add hyperlink for the testing
> .Hyperlinks.Add Anchor:=.Range("F2"), _
> Address:="http://www.mrexcel.com/forum/faq.php", _
> ScreenTip:="MrExcel Message Board FAQ", _
> TextToDisplay:="MrExcel FAQ"
> End With
> End With
> ' Put Body's innerHTML to the strMyPage variable
> strMyPage = GetBodyInnerHTML(Range("F2"))
> ' Print strMyPage into Immediate window of VBE
> Debug.Print strMyPage
> End Sub
> 
> 
> Function GetBodyInnerHTML(Cell As Range, Optional WaitSeconds As Long = 10) As String
> ' ZVI:2015-04-20 http://www.mrexcel.com/forum/excel-questions/553580-visual-basic-applications-macro-already-open-ie-window-2.html
> ' Arguments:
> '   Cell        - the cell with hyperlink to the web page
> '   WaitSeconds - (optional) timeout in seconds for IE navigation
> ' Returns InnerHTML of the web page referenced in the hyperlink of the Cell
> ' (already open IE window is used if exists)
> Dim IE As Object, w As Object
> Dim t As Single
> Dim Url As String
> For Each w In CreateObject("Shell.Application").Windows
> If w.Name = "Windows Internet Explorer" Then
> ' Get IE
> 'Debug.Print "IE is already open" ' <-- for testing
> Set IE = w
> Exit For
> End If
> Next
> If IE Is Nothing Then
> ' Create IE
> Set IE = CreateObject("InternetExplorer.Application")
> IE.Silent = True
> IE.Visible = True
> 'Debug.Print "New IE" ' <-- for testing
> End If
> ' Get url from the cell
> If Cell.Hyperlinks.Count > 0 Then
> ' Hyperlink object is present in the cell
> Url = Cell.Hyperlinks(1).Address
> Else
> ' May be hyperlink is in the cell's value (text)
> Url = Cell.Value
> End If
> ' Do navigation
> IE.Navigate Url
> ' Charge the timeout
> t = Timer + WaitSeconds
> ' Wait for "IE is ready" state
> While IE.ReadyState <> 4 And Timer < t: DoEvents: Wend
> ' Wait for "IE.Document is completely downloaded" state
> If Timer < t Then
> While IE.Document Is Nothing And Timer < t: DoEvents: Wend
> Else
> Err.Raise vbObjectError + 513, , "Timeout happens: " & WaitSeconds & " seconds"
> End If
> ' Return Body's innerHTML
> GetBodyInnerHTML = IE.Document.Body.innerHTML
> ' Clean the memory of object variables
> Set w = Nothing
> Set IE = Nothing
> End Function



Hello ZVI,

I am revisiting my old post and trying your code.

I have to use IE 8 per companies guidelines.

I get an error on this line of your code:



		Rich (BB code):
__


    Err.Raise vbObjectError + 513, , "Timeout happens: " & WaitSeconds & " seconds"


The error message states: Timeout happens 10 seconds.

Do I need to increase the time for the timeout?


----------



## dhustwayte

ZVI said:


> Hi Eric,
> Welcome to MrExcel !
> Function GetIeByTitle finds IE window by window title and returns IE object.
> See example of the usage in Test1 subroutine.
> 
> 
> Rich (BB code):
> __
> 
> 
> 
> ' ZVI:2013-03-19 Get IE object of already open window by its title
> ' Arguments:
> '   Title     -  title of the searchied IE window
> '   [IsLike]  -  False/True = exact/partial searching, default is False
> '   [IsFocus] -  False/True = don't_activate/activate IE window, default is False
> Function GetIeByTitle(Title, Optional IsLike As Boolean, Optional IsFocus As Boolean) As Object
> Dim w As Object
> For Each w In CreateObject("Shell.Application").Windows
> With w
> If .Name = "Windows Internet Explorer" Then
> If IsLike Then
> If InStr(1, .LocationName & " - " & .Name, Title, vbTextCompare) > 0 Then
> ' Partial title of window is found - activate IE window
> If IsFocus Then
> w.Visible = False
> w.Visible = True
> End If
> Set GetIeByTitle = w
> Exit For
> End If
> Else
> If StrComp(.LocationName & " - " & .Name, Title) = 0 Then
> ' Title of window is found - activate IE window
> If IsFocus Then
> w.Visible = False
> w.Visible = True
> End If
> Set GetIeByTitle = w
> Exit For
> End If
> End If
> End If
> End With
> Next
> Set w = Nothing
> End Function
> 
> Sub Test1()
> Dim IE As Object
> Set IE = GetIeByTitle("VBA Macro For Already Open IE Window", True, True)
> IE.Navigate "http://www.mrexcel.com/forum/excel-questions/553580-visual-basic-applications-macro-already-open-ie-window-2.html#post3423470"
> End Sub
> 
> Regards



Hi,

I have been trying to get this to work for some time now but I have a few issues with running.  

For some reason the w.visible = true does not activate the window and all the other codes on this thread simply debug.print the site title and not select it.  

Am I missing something simple here?  Ultimately I just want to activate a window and copy its contents to a worksheet.

Thanks in advance


----------



## RL101

Hi all,

I'm looking to create a VBA macro which will be ran from Excel (2003 or 2010) & which works with Internet Explorer. I have added 'Microsoft Internet Controls' to VBA References, and have looked at plenty of VBA code on the forum which opens & then navigates to specific websites. 

However, what I need is for this macro to affect an already open IE window.

Does anyone have an idea of the syntax / command to have excel "select" a specific IE window already open? 

Many thanks!


----------



## erik4899

ZVI, 

Great stuff!!! I need to accomplish the identical task, but must do using Chrome.  Any assistance would be greatly appreciated.

Thanks







ZVI said:


> Hi & Welcome to the Board!
> Try this:
> 
> 
> Rich (BB code):
> __
> 
> 
> 
> ' ZVI:2011-05-30 VBA Macro For Already Open IE Window
> ' Reference required: Tools - References - Microsoft Internet Controls
> Sub GetIE()
> 
> Dim shellWins As ShellWindows
> Dim IE As InternetExplorer
> 
> Set shellWins = New ShellWindows
> 
> If shellWins.Count > 0 Then
> ' Get IE
> Set IE = shellWins.Item(0)
> Else
> ' Create IE
> Set IE = New InternetExplorer
> IE.Visible = True
> End If
> 
> IE.Navigate "http://support.microsoft.com/kb/q176792/"
> 
> Set shellWins = Nothing
> Set IE = Nothing
> 
> End Sub
> 
> Regards,


----------



## VBAisFun

Good Evening!
Vladimir's codes on page one worked well for me for weeks.
It used to open Microsoft Edge (Windows 10 Browser).
However, yesterday my program started to struggle.
So I tested the original codes from this thread and they do not work anymore on my computer.

Bilder-Upload - Kostenlos Fotos hochladen und ins Netz stellen
Bilder-Upload - Kostenlos Fotos hochladen und ins Netz stellen

Thank you for your help!


----------



## sheikhmisbah

ZVI said:


> Late binding version, reference to Microsoft Internet Controls is not required:
> 
> 
> Rich (BB code):
> __
> 
> 
> 
> Sub GetIE_LateBinding()
> 
> Dim IE As Object
> 
> With CreateObject("Shell.Application").Windows
> 
> If .Count > 0 Then
> ' Get IE
> Set IE = .Item(0) ' or .Item(.Count - 1)
> Else
> ' Create IE
> Set IE = CreateObject("InternetExplorer.Application")
> IE.Visible = True
> End If
> 
> IE.Navigate "http://support.microsoft.com/kb/q176792/"
> 
> Set IE = Nothing
> 
> End With
> 
> End Sub
> 
> P.S. Window of any MS Explorer can be catched, not only of MS Internet Explorer.



Hi Vladimir,

Thank you for the above code which helps me to open web page in same tab instead of to open second window or tab.

I need your help to go next step. using your above code i would like to add the following steps :

1 - Copy Cell A2 (sheet name : Sheet1)

2 - Go to Opened tab "www......... [ using Valadimir code GetIE_LateBinding() which is working perfectly]

3 - Paste the above copied cell value (eg A2) in Job Number Box [ HTML CODING
input name="0_31"tabindex="2" title="Job Number" class="textfieldautosuggesttextfield" id="C0_31" 

4 - Go & Click the search button to search above job number [ HTML Coding
img name="hc_Find" title="Find(Ctrl+Alt+I)" id="hc_Find" ***********="this.src='/jde/img/hc_Findmo.gif'"**********="this.src='/jde/img/hc_Find.gif'"*******="javascript:JDEDTAFactory.getInstance('').post('0_15')"alt="Find (Ctrl+Alt+I)" src="/jde/img/hc_Find.gif"border="0"

5 - Click button >| to go Last line [HTML Coding

a title="Go to end"id="GOTOLAST0_1" style="text-decoration: none;"href="javascript:*******=JDEDTAFactory.getInstance('').post('gLS0_1')"><imgname="jdehtmlGridDown" title="Go to end" id="jdehtmlGridDown"***********="this.src='/jde/img/alta/grid/last_ovr.png'"**********="this.src='/jde/img/alta/grid/last_ena.png'"*******="" alt="Go to end"src="/jde/img/alta/grid/last_ena.png" border="0"></a>

img name="jdehtmlGridDown"title="Go to end" id="jdehtmlGridDown"***********="this.src='/jde/img/alta/grid/last_ovr.png'"**********="this.src='/jde/img/alta/grid/last_ena.png'"*******="" alt="Go to end"src="/jde/img/alta/grid/last_ena.png" border="0">

6 - Click export button to Export data. HTML Coding

Script  jdeWebGUIstartMenu(px"ToolsMenu");
jdeWebGUIaddMenuItem("ToolsMenu","Export Grid     Data","javascript:toolsExitSelected('ExportData0010_1', '')","MENU","Export_To_Excel","Menu Item","",false,"","","false","");

7 - Click Continue button to save the above export data :

a tabindex="-1" title="Continue(Ctrl+Alt+E)" style="text-decoration: none;"><imgname="hc1" title="Continue (Ctrl+Alt+E)" id="hc1"***********="this.src='/jde/img/hc1mo.gif'"**********="this.src='/jde/img/hc1.gif'" *******="checkExportParams('');"alt="Continue (Ctrl+Alt+E)" src="/jde/img/hc1.gif"border="0"></a>

img name="hc1" title="Continue(Ctrl+Alt+E)" id="hc1"***********="this.src='/jde/img/hc1mo.gif'"**********="this.src='/jde/img/hc1.gif'"*******="checkExportParams('');" alt="Continue (Ctrl+Alt+E)"src="/jde/img/hc1mo.gif" border="0">

8 - after save the above export data go to next cell (A3)

9 - stop looping if Column A get blank (means end of job numbers) & show the msg Total Job numbers has been exported.

Any idea for the above ?

Your cooperation would be really really appreciated.

Best Regards,

Misbah


----------



## Nahuster

ZVI said:


> Hi Matt,
> Welcome to the Board!
> Seems it's a bit different task, hope you mean something like this:
> 
> 
> Rich (BB code):
> __
> 
> 
> ' Code of Module1
> 
> Sub LoopIE(Optional Cancel As Boolean)
> 
> ' --> Settings, change to suit
> Const Link = "www.google.com"
> Const RepeatMinutes = 5   ' Time interval in minutes for repeating of this macro
> Const WaitSeconds = 10    ' Waiting time interval in secondss for "IE is ready" state
> ' <-- End of settings
> 
> Dim t As Single
> Static IE As Object, t1 As Double
> 
> ' Cancel the repeating of this macro
> If Cancel Then
> ' Cancel schedule
> If t1 Then Application.OnTime t1, "LoopIE", Schedule:=False
> t1 = 0
> ' Reset IE object
> On Error Resume Next
> If Not IE Is Nothing Then IE.Quit
> Set IE = Nothing
> Exit Sub
> End If
> 
> ' Trap error
> On Error GoTo exit_
> 
> ' Main
> If IE Is Nothing Then Set IE = CreateObject("InternetExplorer.Application")
> With IE
> .Visible = True
> ' Disable pop-up msgs
> .Silent = True
> ' Navigate
> Application.StatusBar = "Navigating to: " & Link & " ..."
> .Navigate Link
> ' Charge the timeout
> t = Timer + WaitSeconds
> ' Wait for "IE is ready" state
> Application.StatusBar = "Waiting for IE's complete state..."
> While .readyState <> 4 And Timer < t: DoEvents: Wend
> ' Wait for "IE.Document is completely downloaded" state
> If Timer < t Then
> Application.StatusBar = "Waiting for Document's downloaded state..."
> While .Document Is Nothing And Timer < t: DoEvents: Wend
> Else
> Err.Raise vbObjectError + 513, , "Timeout happens: " & WaitSeconds & " seconds"
> End If
> End With
> 
> exit_:
> 
> ' Inform about error
> If Err.Number <> 0 Then
> Application.StatusBar = "NavigateTo: " & Replace(Err.Description, vbLf, " - ")
> ' Show error message
> MsgBox Err.Description, vbExclamation, "Error"
> ' Reset IE object
> On Error Resume Next
> If Not IE Is Nothing Then IE.Quit
> Set IE = Nothing
> Else
> ' Clear StatusBar
> Application.StatusBar = False
> ' Charge schedule
> t1 = Now + TimeSerial(0, RepeatMinutes, 0)
> Application.OnTime t1, "LoopIE"
> End If
> 
> End Sub
> 
> ' Macro for the Start button
> Sub Start()
> LoopIE
> End Sub
> 
> ' Cancel schedule and quit IE
> Sub Auto_Close()
> LoopIE Cancel:=True
> End Sub
> 
> 
> Regards





Hello,
             I know it's been a while since this thread was active but I can't find the answer anywhere.

Here's what I've got:


VBA Function - Find specific internet explorer open tab
Hello there,


      I'm building a macro to manage some tickets and I now want the application to get some data from a website.

 1st I need it to sort out which tab to use, the only value that's unique is the ticket number, in this case "INC0347911"


 I've seen a few places in the HTML code where the ticket number is located


Here's a chunk of the site 



		HTML:
__


******** type="text/ng-template" id="angular.do?sysparm_type=get_partial&name=sn_reference_popover_button.xml">
  <button ng-click="togglePopover($event)" tabindex="{{::buttonTabIndex}}" data-for="sys_display.{{ref}}" name="lookup.{{ref}}" id="lookup.{{ref}}" title="Lookup using list" type="button" class="btn btn-default sn-popover-complex icon icon-search"><span class="sr-only">Lookup using list</span></button>*********><div class="section_header_div_no_scroll form_title" data-form-title="INC0347911" id="incident.form_header"><input type="hidden" value="incident.do" id="section_form_id"></input><span tab_caption="Incident" id="section_tab.bf1d96e3c0a801640190725e63f8ac80" class="tabs2_section tabs2_section_0 tabs2_section0" tab_caption_raw="" data-header-only="true" data-section-id="bf1d96e3c0a801640190725e63f8ac80"><span class="section " id="section-bf1d96e3c0a801640190725e63f8ac80" data-header-only="true"><nav class="navbar navbar-default section_zero " data-id="bf1d96e3c0a801640190725e63f8ac80" data-type="section_head"><div class="container-fluid"><div class="navbar-header"><input type="HIDDEN" id="sysverb_back"></input><button title="Back" class="btn btn-default icon-chevron-left navbar-btn" *******="return gsftSubmit(this.previousSibling)"><span class="sr-only">Back</span></button><button title="Additional actions" class="btn btn-icon icon-menu navbar-btn" *******="contextShow(event, '1', 200, grabOffsetTop(this) + 20, grabOffsetLeft(this) + 24);event.cancelBubble=true;Event.stop(event);"><span class="sr-only">Additional actions</span></button><h2 draggable="true" ondragstart="event.dataTransfer.setData('text', Object.toJSON({ icon: 'form', url: ****************.href, title: g_form.getTitle(), table: g_form.getTableName() }))" class="form_header navbar-title navbar-title-twoline"><input type="HIDDEN" name="sysverb_view_change" id="sysverb_view_change"></input><div title="Current View: Default view (click me for other views)" class="pointerhand" *******="contextShow(event, 'labelMenu', -1, 0, 0);event.cancelBubble=true;"><div class="navbar-title-caption">Incident</div><div class="navbar-title-display-value">INC0347911</div></div></h2></div><div class="navbar-right"><span style="display: ;" id="section_head_right.bf1d96e3c0a801640190725e63f8ac80">********>NOW.streamLinkTarget = '';

 
Here are the two places I've found where that ticket number appears:



		HTML:
__


class="section_header_div_no_scroll form_title" data-form-title="INC0347911" id="incident.form_header"




		HTML:
__


class="navbar-title-caption">Incident</div><div class="navbar-title-display-value">INC0347911

 
 So I guess my question is how to look into all the available tabs and look for that particular class, to make sure I'm modifying the right tab.
Could someone point me in the right direction? I've been brwosing the web and came up with many chunks of code but they usually need the name of the tab or the URL, but there's no way to pick it up through URL because the ticket numebr is not in it, so I can't make it choose one ticket from the other 20 that are open.
Help please?

Thank you 



UPDATE:
What I need to do is for the code to search through the HTML of my open instances of internet explorer and look for those INC numbers. Say I have three tabs open, "INC001", "INC007" and "INC010" and I only want it to look for "INC007" and bring it upwards or just zero on it so the rest of the code works and the right ticket gets filled.
I don't know, could you please let me know if you know how to do this? or point me in the right direction? I think the problem may also be that I don't know what to ask for...

THANK YOU


----------



## ZVI

Nahuster said:


> ...
> What I need to do is for the code to search through the HTML of my open instances of internet explorer and look for those INC numbers. Say I have three tabs open, "INC001", "INC007" and "INC010" and I only want it to look for "INC007" and bring it upwards or just zero on it so the rest of the code works and the right ticket gets filled.


 Hi Nahuster,
As to your PM and the above post, try this code:


		Rich (BB code):
__


Sub Main()
  Dim IE As Object, HtmlText As String
  HtmlText = "data-form-title=""INC0347911"""   ' <-- the search HTML string
  Set IE = GetIeByHtmlText(HtmlText)
  If IE Is Nothing Then
    MsgBox "HtmlText is not found in any open IE instances"
  Else
     MsgBox "HtmlText is found in the open IE instance with URL:" & vbLf & IE.LocationURL
  End If
End Sub
 
Function GetIeByHtmlText(HtmlText As String) As Object
' ZVI: 2017-03-18 https://www.mrexcel.com/forum/excel-questions/553580-visual-basic-applications-macro-already-open-ie-window-2.html#post4781479
  Dim w As Object
  Dim i As Long
  For Each w In CreateObject("Shell.Application").Windows
    If w.Name = "Windows Internet Explorer" Then
      i = InStr(1, w.Document.Body.innerHTML, HtmlText, vbTextCompare)
      If i > 0 Then
        Set GetIeByHtmlText = w
        Exit For
      End If
    End If
  Next
End Function

Regards


----------



## ZVI

sheikhmisbah said:


> Hi Vladimir,
> 
> Thank you for the above code which helps me to open web page in same tab instead of to open second window or tab.
> 
> I need your help to go next step. using your above code i would like to add the following steps :
> 
> 1 - Copy Cell A2 (sheet name : Sheet1)
> 
> 2 - Go to Opened tab "www......... [ using Valadimir code GetIE_LateBinding() which is working perfectly]
> 
> 3
> ...
> 9


Hi Misbah,

As you have already mentioned in the point #2 the GetIE_LateBinding() is working which is good.
 But all your other points are about parsing the web page which is not the subject of this thread. 
It is better to create new thread(s) for those points.

Best Regards


----------



## Nahuster

ZVI said:


> Hi Nahuster,
> As to your PM and the above post, try this code:
> 
> 
> Rich (BB code):
> __
> 
> 
> Sub Main()
> Dim IE As Object, HtmlText As String
> HtmlText = "data-form-title=""INC0347911"""   ' <-- the search HTML string
> Set IE = GetIeByHtmlText(HtmlText)
> If IE Is Nothing Then
> MsgBox "HtmlText is not found in any open IE instances"
> Else
> MsgBox "HtmlText is found in the open IE instance with URL:" & vbLf & IE.LocationURL
> End If
> End Sub
> 
> Function GetIeByHtmlText(HtmlText As String) As Object
> ' ZVI: 2017-03-18 https://www.mrexcel.com/forum/excel-questions/553580-visual-basic-applications-macro-already-open-ie-window-2.html#post4781479
> Dim w As Object
> Dim i As Long
> For Each w In CreateObject("Shell.Application").Windows
> If w.Name = "Windows Internet Explorer" Then
> i = InStr(1, w.Document.Body.innerHTML, HtmlText, vbTextCompare)
> If i > 0 Then
> Set GetIeByHtmlText = w
> Exit For
> End If
> End If
> Next
> End Function
> 
> Regards






Really? was it that simple? WOW, I was actually looking for that bit that searches within HTML but didn't know how to get it.
I can't try it here because I work on a VDA and can't use it from home but will let you know on Monday. 
Anyway, THANK YOU VERY MUCH, I've been asking around and this is the first reply I get in weeks.
Again, thank you Vladimir

Cheers!


----------



## ZVI

VBAisFun said:


> Good Evening!
> Vladimir's codes on page one worked well for me for weeks.
> It used to open Microsoft Edge (Windows 10 Browser).
> However, yesterday my program started to struggle.
> So I tested the original codes from this thread and they do not work anymore on my computer.
> 
> Bilder-Upload - Kostenlos Fotos hochladen und ins Netz stellen
> Bilder-Upload - Kostenlos Fotos hochladen und ins Netz stellen
> 
> Thank you for your help!


Good evening! 
Sorry for too late incoming to your post – has not tracked this thread.
It seems that once opening & closing of IE11 will solve that issue. 
Hope this will help someone with such a problem.
Best Regards


----------



## ZVI

Nahuster said:


> Really? was it that simple? WOW, I was actually looking for that bit that searches within HTML but didn't know how to get it.
> I can't try it here because I work on a VDA and can't use it from home but will let you know on Monday.
> Anyway, THANK YOU VERY MUCH, I've been asking around and this is the first reply I get in weeks.
> Again, thank you Vladimir
> 
> Cheers!


Wish you a lot of useful answers in this forum!


----------



## Nahuster

ZVI said:


> Hi Nahuster,
> As to your PM and the above post, try this code:
> 
> 
> Rich (BB code):
> __
> 
> 
> Sub Main()
> Dim IE As Object, HtmlText As String
> HtmlText = "data-form-title=""INC0347911"""   ' <-- the search HTML string
> Set IE = GetIeByHtmlText(HtmlText)
> If IE Is Nothing Then
> MsgBox "HtmlText is not found in any open IE instances"
> Else
> MsgBox "HtmlText is found in the open IE instance with URL:" & vbLf & IE.LocationURL
> End If
> End Sub
> 
> Function GetIeByHtmlText(HtmlText As String) As Object
> ' ZVI: 2017-03-18 https://www.mrexcel.com/forum/excel-questions/553580-visual-basic-applications-macro-already-open-ie-window-2.html#post4781479
> Dim w As Object
> Dim i As Long
> For Each w In CreateObject("Shell.Application").Windows
> If w.Name = "Windows Internet Explorer" Then
> i = InStr(1, w.Document.Body.innerHTML, HtmlText, vbTextCompare)
> If i > 0 Then
> Set GetIeByHtmlText = w
> Exit For
> End If
> End If
> Next
> End Function
> 
> Regards




Hello Vladimir, sorry to bother you again.
I've tried that and couldn't make it work.
I've tried using the line as you put it:
 HtmlText = "data-form-title=""INC0347911"""   
I also tried with just the INC number and searching for a class...
This one: 
class
 ="navbar-title-display-value">INC0357749<

But couldn't make it work.
Is there anything else to do? or do you think I'm doing something wrong?
I can't find where the issue is.

If I run the sub it gives me the negative MsgBox

If I try running the function it says :

IE window with this Title is not found: ""

Thank you


----------



## RL101

Hi all,

I'm looking to create a VBA macro which will be ran from Excel (2003 or 2010) & which works with Internet Explorer. I have added 'Microsoft Internet Controls' to VBA References, and have looked at plenty of VBA code on the forum which opens & then navigates to specific websites. 

However, what I need is for this macro to affect an already open IE window.

Does anyone have an idea of the syntax / command to have excel "select" a specific IE window already open? 

Many thanks!


----------



## ZVI

Nahuster said:


> ... couldn't make it work.
> Is there anything else to do? or do you think I'm doing something wrong?
> I can't find where the issue is.
> 
> If I run the sub it gives me the negative MsgBox
> 
> If I try running the function it says :
> 
> *IE window with this Title is not found:* ""


Looks like you mixed part of the code from post #75 with some previous code because the above Red message is not present in the code of post #75.
Open manually in IE these links:
http://www.mrexcel.com/
https://www.mrexcel.com/forum/faq.php
and some other web pages.

 Add the new Module to the VBA project and put the below code to it, which is the same as in the post #75 but with HtmlText = "wp-image-763" for url = http://www.mrexcel.com/
Then run the Main() 


		Rich (BB code):
__


Sub Main()
  Dim IE As Object, HtmlText As String
  HtmlText = "wp-image-763"   ' <-- this string is present in the html code of main mrexcel.com web page
  Set IE = GetIeByHtmlText(HtmlText)
  If IE Is Nothing Then
    MsgBox "HtmlText is not found in any open IE instances"
  Else
     MsgBox "HtmlText is found in the open IE instance with URL:" & vbLf & IE.LocationURL
  End If
End Sub
 
Function GetIeByHtmlText(HtmlText As String) As Object
' ZVI: 2017-03-18 https://www.mrexcel.com/forum/excel-questions/553580-visual-basic-applications-macro-already-open-ie-window-2.html#post4781479
  Dim w As Object
  Dim i As Long
  For Each w In CreateObject("Shell.Application").Windows
    If w.Name = "Windows Internet Explorer" Then
      i = InStr(1, w.Document.Body.innerHTML, HtmlText, vbTextCompare)
      If i > 0 Then
        Set GetIeByHtmlText = w
        Exit For
      End If
    End If
  Next
End Function

Message will say that already open instance of IE is found in the main mrexcel web page


----------



## sharonr

Hi,

Is there a vba code where:
1. it open the internet explorer first
2. type something in search column (eg.Happy Birthday). We get the images
3. select the image and by right clicking on the image to save, it should save in the folder.

Could any one please help me with this.

Thank You


----------



## Dexter666

I've tried Your original code and it's doing nothing. I use 64-bit Excel (the reference to MS Internet Controls is set). Can You hehlp me out?



ZVI said:


> Hi & Welcome to the Board!
> Try this:
> 
> 
> Rich (BB code):
> __
> 
> 
> 
> ' ZVI:2011-05-30 http://www.mrexcel.com/forum/showthread.php?t=553580
> ' Reference required: Tools - References - Microsoft Internet Controls
> Sub GetIE()
> 
> Dim shellWins As ShellWindows
> Dim IE As InternetExplorer
> 
> Set shellWins = New ShellWindows
> 
> If shellWins.Count > 0 Then
> ' Get IE
> Set IE = shellWins.Item(0)
> Else
> ' Create IE
> Set IE = New InternetExplorer
> IE.Visible = True
> End If
> 
> IE.Navigate "http://support.microsoft.com/kb/q176792/"
> 
> Set shellWins = Nothing
> Set IE = Nothing
> 
> End Sub
> 
> Regards,


----------



## ZVI

Dexter666 said:


> I've tried Your original code and it's doing nothing. I use 64-bit Excel (the reference to MS Internet Controls is set). Can You hehlp me out?


May be that link is broken now, try this:


		Rich (BB code):
__


Sub GetIE_01()
 
  Dim shellWins As ShellWindows
  Dim IE As InternetExplorer
 
  Set shellWins = New ShellWindows
 
  If shellWins.Count > 0 Then
    ' Get IE
    Set IE = shellWins.Item(0)
  Else
    ' Create IE
    Set IE = New InternetExplorer
  End If
 
  IE.Navigate "http://www.mrexcel.com/forum/index.php"
 
  ' Activate IE
  IE.Visible = False
  IE.Visible = True
 
  Set shellWins = Nothing
  Set IE = Nothing
 
End Sub


----------



## Dexter666

Ah... That didn't cross my mind... Yeah, it works. Thanks


----------



## Norgewalk

ZVI said:


> Hi & Welcome to the Board!
> Try this code:
> 
> 
> Rich (BB code):
> __
> 
> 
> 
> Function NavigateTo(Link As String, Optional WaitSeconds = 5) As Long
> ' ZVI:2011-08-04 http://www.mrexcel.com/forum/showthread.php?t=553580
> ' Navigate (Internet)Explorer to the Link with [WaitSeconds=5] timeout.
> ' If (Internet)Explorer is already navigated to the Link then it's just activated,
> ' else the new (Internet)Explorer is navigated to the Link.
> ' Returns  error number (zero at success)
> ' Note: comment "Application.StatusBar" lines for VB & VBScript compatibility
> 
> Dim i As Long, t As Single, Url As String, w As Object, wUrl As String
> 
> ' Uniform Link string
> Url = Trim(Replace(Replace(Link, "%20", " "), "", "/"))
> ' Find "://" prefix
> i = InStr(Url, "://")
> If i > 1 And i < 7 Then Url = Mid(Url, i + 3)
> ' Delete "/" at the end
> If Right(Url, 1) = "/" Then Url = Left(Url, Len(Url) - 1)
> 
> ' Seach Link in IE windows
> Application.StatusBar = "Finding link: " & Link & " ..."
> For Each w In CreateObject("Shell.Application").Windows
> ' Uniform LocationURL string
> wUrl = Trim(Replace(Replace(w.LocationURL, "%20", " "), "", "/"))
> ' Find "://" prefix
> i = InStr(wUrl, "://")
> If i > 1 And i < 7 Then wUrl = Mid(wUrl, i + 3)
> ' Del 3d "/" in prefix for local Link
> If Mid(wUrl, 1, 1) = "/" Then wUrl = Mid(wUrl, 2)
> ' Delete "/" at the end
> If Right(wUrl, 1) = "/" Then wUrl = Left(wUrl, Len(wUrl) - 1)
> If StrComp(Url, wUrl, 1) = 0 Then
> ' Link is found - activate it's IE window
> w.Visible = True
> Exit For
> Else
> wUrl = ""
> End If
> Next
> 
> ' If Link is not found then create new IE and navigate to the Link
> On Error Resume Next
> If Len(wUrl) = 0 Then
> With CreateObject("InternetExplorer.Application")
> ' Disable pop-up msgs
> .Silent = True
> ' Navigate
> Application.StatusBar = "Navigating to: " & Link & " ..."
> .Navigate Link
> ' Charge the timeout
> t = Timer + WaitSeconds
> ' Wait for "IE is ready" state
> Application.StatusBar = "Waiting for IE's complete state..."
> While .readyState <> 4 And Timer < t: DoEvents: Wend
> ' Wait for "IE.Document is completely downloaded" state
> If Timer < t Then
> Application.StatusBar = "Waiting for Document's downloaded state..."
> While .Document Is Nothing And Timer < t: DoEvents: Wend
> Else
> Err.Raise vbObjectError + 513, , "Timeout happens: " & WaitSeconds & " seconds"
> End If
> ' Activate IE
> Application.StatusBar = False
> If Err Then .Quit Else .Visible = True
> End With
> End If
> 
> ' Release the memory of object variable
> Set w = Nothing
> 
> ' Return error number (zero if successful)
> NavigateTo = Err.Number
> 
> ' Show error message
> If Err.Number <> 0 Then
> Application.StatusBar = "NavigateTo: " & Replace(Err.Description, vbLf, " - ")
> ' Uncomment the line below to show error message
> 'MsgBox Err.Description, vbExclamation, "NavigateTo"
> End If
> 
> End Function
> 
> 
> Example of the calling:
> 
> 
> Rich (BB code):
> __
> 
> 
> 
> Sub Test_NavigateTo()
> 
> ' Define the test number
> Const TEST = 2
> 
> Select Case TEST
> Case 1: NavigateTo "about:blank"
> Case 2: NavigateTo "www.mrexcel.com/forum/showthread.php?t=553580"
> Case 3: NavigateTo "http://www.google.com/"
> Case 4: NavigateTo "http://support.microsoft.com/kb/q176792/"
> Case 5: NavigateTo "C:\Temp"
> End Select
> 
> End Sub






This is wonderful, but there is something I can't figure out. 

If the page already exists, how do you refresh it instead of just activating it?


----------



## imgaur7

That was great Vladimir, so close to my requirement and to get an idea about the same.

I was looking to open a list of web links in IE and wait for 5 sec.
Close the active IE page
Load another web link from excel cell A1 (and wait for 5 sec)
 and loop the process till last value in cell A1


I tried this code



		Code:
__


Sub OpenLinks()
    Dim Cell As Range
    Set LinkRng = Range("A1").CurrentRegion.Columns(1)
    On Error Resume Next
    For Each Cell In LinkRng.Cells
        Cell.Hyperlinks(1).Follow
        Application.Wait (Now + TimeValue("00:00:05"))
        Application.Quit
        'IE.Quit
        Next
    On Error GoTo 0
End Sub


but it keep on opening all the web pages one after another, which is different from what I am looking for

Kindly see if it is possible


----------



## baralus

ZVI said:


> Late binding version, reference to Microsoft Internet Controls is not required:
> 
> 
> Rich (BB code):
> __
> 
> 
> 
> Sub GetIE_LateBinding()
> 
> Dim IE As Object
> 
> With CreateObject("Shell.Application").Windows
> 
> If .Count > 0 Then
> ' Get IE
> Set IE = .Item(0) ' or .Item(.Count - 1)
> Else
> ' Create IE
> Set IE = CreateObject("InternetExplorer.Application")
> IE.Visible = True
> End If
> 
> IE.Navigate "http://support.microsoft.com/kb/q176792/"
> 
> Set IE = Nothing
> 
> End With
> 
> End Sub
> 
> P.S. Window of any MS Explorer can be catched, not only of MS Internet Explorer.




I tried to use this code and add "Do while IE.readystate = 4: do events:loop" after the navigate part, but for some reason it loops endlessly. I did that because i want a confirmation that the webpage has already load if ever i will add other codes


----------



## ashleedawg

...works great, *and *it loads to a _very convenient_ demo page, lol.


----------



## aadityajain08

Hi,

When i am using the below code i.e.

Dim shell As ShellWindows

i am getting the compile error (User defined type not defined). Please help.  

Regards:
Aditya jain


----------



## RL101

Hi all,

I'm looking to create a VBA macro which will be ran from Excel (2003 or 2010) & which works with Internet Explorer. I have added 'Microsoft Internet Controls' to VBA References, and have looked at plenty of VBA code on the forum which opens & then navigates to specific websites. 

However, what I need is for this macro to affect an already open IE window.

Does anyone have an idea of the syntax / command to have excel "select" a specific IE window already open? 

Many thanks!


----------



## RoryA

Per the original:



> ' Reference required: Tools - References - Microsoft Internet Controls


----------



## aadityajain08

Thanks Rory for posting the Solution. It worked and now i am not getting any Compilation error. However, my problem is still not resolved. 
When i checked for the shell window, it is not shell window with no different URL attached, it is Just a pop-up page with no URL and i need to access the same. 
The pop-up page is getting appear from the below code (DO-Modal DIV).


		Code:
__


<div class="PSMODAL" id="pt_modals" style="display: block; background-color: transparent;">
	<div class="popupDragFrame" id="ptModalShadow" style="cursor: nw-resize;"> 
	</div><div id="ptMod_0" style="z-index: 9999;">
		<div class="PSMODALTABLE" id="ptModTable_0" style="left: 270.5px; top: 25px; width: 859px; height: 120px;">
			<div class="PSMODALHEADER" id="ptModHeader_0" style="display: block;">
			<div class="PSMODALCONTENT" id="ptModContent_0"> 	
			<div class="PSMODALBOTTOM" id="ptModBottom_0" style="height: 14px; display: block;">
		</div>
	</div>	
</div>

I have written the below code but now stuck to access the popup page. Please help



		Code:
__


Sub Collector_Proc()
 
'Variable Declaration
Dim IE As Object
Dim AJ As String
Dim K As String
Dim rl As String
'Set iePopup = CreateObject("InternetExplorer.application")
Dim shell As ShellWindows
'Variable Initialization
Set shell = New ShellWindows
Set IE = CreateObject("InternetExplorer.application")
Set sh = ThisWorkbook.Sheets("Collector")
Set CR = ThisWorkbook.Sheets("Credentials")
'URL capture and Navigation
AJ = CR.Range("B5").Value
IE.Navigate AJ
IE.Visible = True
'IE processing wait logic
Application.Wait (Now + TimeValue("00:00:03"))
While IE.Busy = True
           DoEvents
      Wend
With IE
    Do Until .readyState = 4: DoEvents: Loop
    
End With
      
'Credentials Passing and processing
IE.document.getelementbyid("userid").Focus
IE.document.getelementbyid("userid").Value = ""
IE.document.getelementbyid("userid").Value = CR.Cells(1, 2).Value
IE.document.getelementbyid("pwd").Focus
IE.document.getelementbyid("pwd").Value = CR.Cells(2, 2).Value
Set tags = IE.document.getElementsByTagName("input")
For Each tagx In tags
    If tagx.Value = "Sign In" Then
        tagx.Click
        Exit For
    End If
Next
'IE processing wait logic
Application.Wait (Now + TimeValue("00:00:03"))
        While IE.Busy = True
            DoEvents
        Wend
With IE
    Do Until .readyState = 4: DoEvents: Loop
End With

'Calculation of number of UserID's to process
sh.Cells(2, 6).Value = sh.UsedRange.Rows.Count - 1
'Loop for each user ID
For i = 2 To sh.UsedRange.Rows.Count
    If sh.Cells(i, 1).Value <> "" Then
        If sh.Cells(i, 2).Value <> "Complete" Then
            Set varitm = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.getelementbyid("OPRID_VW_OPRID")
                    varitm.Focus
                    varitm.Value = ""
                    varitm.Value = sh.Cells(i, 1).Value
            Set varitm1 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.getelementbyid("#ICSearch")
                    varitm1.Focus
                    varitm1.Click
            'IE processing wait logic
            Application.Wait (Now + TimeValue("00:00:03"))
                    While IE.Busy = True
                        DoEvents
                    Wend
            With IE
                Do Until .readyState = 4: DoEvents: Loop
            End With
            'Selecting GL Link
            Set varitm2 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_LINKS_OPR_DEF_LINK_GL1")
                    varitm2.Focus
                    varitm2.Click
            'IE processing wait logic
            Application.Wait (Now + TimeValue("00:00:03"))
                    While IE.Busy = True
                        DoEvents
                    Wend
            With IE
                Do Until .readyState = 4: DoEvents: Loop
            End With
            ' Re-setting up GL configuration
            Set varitm3 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_TBL_FS_LEDGER")
                    varitm3.Focus
                    varitm3.Value = ""
            Set varitm4 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_TBL_FS_LEDGER_GROUP")
                    varitm4.Focus
                    varitm4.Value = ""
            Set varitm5 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_TBL_FS_SOURCE")
                    varitm5.Focus
                    varitm5.Value = ""
            Set varitm6 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_TBL_GL_COPY")
                    varitm6.Focus
                    varitm6.Click
            Set varitm7 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_TBL_GL_DELETE_CONTROL")
                    varitm7.Focus
                    varitm7.Click
            Set varitm8 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_TBL_GL_UNPOST_FLG")
                    varitm8.Focus
                    varitm8.Click
            Set varitm9 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_TBL_GL_SKIP_SUMLED_UPD_SW")
                    varitm9.Focus
                    varitm9.Click
            Set varitm10 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_TBL_GL_SKIP_ESSBASE_LOAD")
                    varitm10.Focus
                    varitm10.Click
            'Return to main Tab
            Set varitm10 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("ICTAB_0")
                    varitm10.Focus
                    varitm10.Click
                    'IE processing wait logic
                    Application.Wait (Now + TimeValue("00:00:03"))
                    While IE.Busy = True
                        DoEvents
                    Wend
                    
                    With IE
                        Do Until .readyState = 4: DoEvents: Loop
                        
                    End With
            'Selecting Procurement Link
            Set varitm11 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_LINKS_OPR_DEF_LINK_PM1")
                    varitm11.Focus
                    varitm11.Click
                    'IE processing wait logic
                    Application.Wait (Now + TimeValue("00:00:03"))
                            While IE.Busy = True
                                DoEvents
                            Wend
                            
                    With IE
                        Do Until .readyState = 4: DoEvents: Loop
                        
                    End With
            'clicking Sub-Procurement Link---Open POPUP Window
            Set varitm12 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_PM_WRK_OPR_DEF_APVCHR_PB")
                    varitm12.Focus
                    varitm12.Click
            Application.Wait (Now + TimeValue("00:00:03"))
                    While IE.Busy = True
                        DoEvents
                    Wend
                    
            With IE
                Do Until .readyState = 4: DoEvents: Loop
                
            End With
'Debug.Print IE.LocationName, IE.LocationURL, IE.AddressBar, IE.Application

            For Each IE In shell
            'Print URL for Each Window but only one URL is getting printed as POPUP window dont have URL associated, it is getting open from DO-Modal
            sh.Cells(i + 7, 5).Value = IE.LocationURL
            Exit For
            Next


Please help. This is very necessary for me.

Regards:
Aditya jain


----------



## aadityajain08

Sorry, but HTML Code is not getting upload. Trying with Tags.
Below is code from HTML


		HTML:
__


<div class="PSMODAL" id="pt_modals" style="display: block; background-color: transparent;">
	<div class="popupDragFrame" id="ptModalShadow" style="cursor: nw-resize;"> 
	</div><div id="ptMod_0" style="z-index: 9999;">
		<div class="PSMODALTABLE" id="ptModTable_0" style="left: 270.5px; top: 25px; width: 859px; height: 120px;">
			<div class="PSMODALHEADER" id="ptModHeader_0" style="display: block;">
			<div class="PSMODALCONTENT" id="ptModContent_0">	
			<div class="PSMODALBOTTOM" id="ptModBottom_0" style="height: 14px; display: block;">
		</div>
	</div>	
</div>


----------



## ZVI

Hi, 
I'm not certain in the goal of finding IE windows in your code
but to list all open IE windows you may use this part of the code


		Rich (BB code):
__


  Dim w As Object
  For Each w In CreateObject("Shell.Application").Windows
    If w.Name Like "*Internet Explorer" Then
      Debug.Print w.LocationURL
    End If
  Next


----------



## aadityajain08

Hi Zvi,

Thanks for response. Let me elaborate some more. Upon executing the below code from VBA,


		Code:
__


'clicking Sub-Procurement Link---Open POPUP Window
            Set varitm12 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_PM_WRK_OPR_DEF_APVCHR_PB")
                    varitm12.Focus
                    varitm12.Click


A popup window appear which is not associated with any URL. It is getting appear through the PSMODAL page functionality (just like submit/cancel popup page) 
and there is no URL Bar. Code for html is provided below. 



		HTML:
__


<div class="PSMODAL" id="pt_modals" style="display: block; background-color: transparent;">
	<div class="popupDragFrame" id="ptModalShadow" style="cursor: nw-resize;"> 
	</div><div id="ptMod_0" style="z-index: 9999;">
		<div class="PSMODALTABLE" id="ptModTable_0" style="left: 270.5px; top: 25px; width: 859px; height: 120px;">
			<div class="PSMODALHEADER" id="ptModHeader_0" style="display: block;">
			<div class="PSMODALCONTENT" id="ptModContent_0"> 	
			<div class="PSMODALBOTTOM" id="ptModBottom_0" style="height: 14px; display: block;">
		</div>
	</div>	
</div>


The Popup page which is getting appear, having multiple setups, I need to perform the setup on the popup page, then close the popup page and return to main window.
So the Sequence is like,
Main window > Click on Link > POPUP page> Control transfer to popup page > do modification on POPUP Page > Save POPUP page> Close POPUP page> Conrol to main Page.

Please suggest.

Regards:
Aditya Jain


----------



## ZVI

aadityajain08 said:


> A popup window appear which is not associated with any URL. It is getting appear through the PSMODAL page functionality (just like submit/cancel popup page) and there is no URL Bar.


Even there is no visible URL bar it's one of the IE windows.
Apply the suggested code of the post #94 to your code, then check URL of the popup window printed in the Immediate window of VBE. 
After that just filter that URL in the code by if-then-else.
And use: Set IE = w or just use  w object for further parsing (which is out of this thread goal as for me)


----------



## aadityajain08

Thanks Zvi, I incorporated the code you provided but the "for" loop is getting executed only once and giving the output as the parent URL at immidiate window of VBE.


		Code:
__


Sub Collector_Proc()
 
'Variable Declaration
Dim IE As Object
Dim AJ As String
Dim K As String
Dim rl As String
Dim w As Object
'Set iePopup = CreateObject("InternetExplorer.application")
Dim shell As ShellWindows
'Variable Initialization
Set shell = New ShellWindows
Set IE = CreateObject("InternetExplorer.application")
Set sh = ThisWorkbook.Sheets("Collector")
Set CR = ThisWorkbook.Sheets("Credentials")
'URL capture and Navigation
AJ = CR.Range("B5").Value
IE.navigate AJ
IE.Visible = True
'IE processing wait logic
Application.Wait (Now + TimeValue("00:00:03"))
While IE.Busy = True
           DoEvents
      Wend
With IE
    Do Until .readyState = 4: DoEvents: Loop
    
End With
      
'Credentials Passing and processing
IE.document.getelementbyid("userid").Focus
IE.document.getelementbyid("userid").Value = ""
IE.document.getelementbyid("userid").Value = CR.Cells(1, 2).Value
IE.document.getelementbyid("pwd").Focus
IE.document.getelementbyid("pwd").Value = CR.Cells(2, 2).Value
Set tags = IE.document.getElementsByTagName("input")
For Each tagx In tags
    If tagx.Value = "Sign In" Then
        tagx.Click
        Exit For
    End If
Next
'IE processing wait logic
Application.Wait (Now + TimeValue("00:00:03"))
        While IE.Busy = True
            DoEvents
        Wend
With IE
    Do Until .readyState = 4: DoEvents: Loop
End With

'Calculation of number of UserID's to process
sh.Cells(2, 6).Value = sh.UsedRange.Rows.Count - 1
'Loop for each user ID
For i = 2 To sh.UsedRange.Rows.Count
    If sh.Cells(i, 1).Value <> "" Then
        If sh.Cells(i, 2).Value <> "Complete" Then
            Set varitm = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.getelementbyid("OPRID_VW_OPRID")
                    varitm.Focus
                    varitm.Value = ""
                    varitm.Value = sh.Cells(i, 1).Value
            Set varitm1 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.getelementbyid("#ICSearch")
                    varitm1.Focus
                    varitm1.Click
            'IE processing wait logic
            Application.Wait (Now + TimeValue("00:00:03"))
                    While IE.Busy = True
                        DoEvents
                    Wend
            With IE
                Do Until .readyState = 4: DoEvents: Loop
            End With
            'Selecting GL Link
            Set varitm2 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_LINKS_OPR_DEF_LINK_GL1")
                    varitm2.Focus
                    varitm2.Click
            'IE processing wait logic
            Application.Wait (Now + TimeValue("00:00:03"))
                    While IE.Busy = True
                        DoEvents
                    Wend
            With IE
                Do Until .readyState = 4: DoEvents: Loop
            End With
            ' Re-setting up GL configuration
            Set varitm3 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_TBL_FS_LEDGER")
                    varitm3.Focus
                    varitm3.Value = ""
            Set varitm4 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_TBL_FS_LEDGER_GROUP")
                    varitm4.Focus
                    varitm4.Value = ""
            Set varitm5 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_TBL_FS_SOURCE")
                    varitm5.Focus
                    varitm5.Value = ""
            Set varitm6 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_TBL_GL_COPY")
                    varitm6.Focus
                    varitm6.Click
            Set varitm7 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_TBL_GL_DELETE_CONTROL")
                    varitm7.Focus
                    varitm7.Click
            Set varitm8 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_TBL_GL_UNPOST_FLG")
                    varitm8.Focus
                    varitm8.Click
            Set varitm9 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_TBL_GL_SKIP_SUMLED_UPD_SW")
                    varitm9.Focus
                    varitm9.Click
            Set varitm10 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_TBL_GL_SKIP_ESSBASE_LOAD")
                    varitm10.Focus
                    varitm10.Click
            'Return to main Tab
            Set varitm10 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("ICTAB_0")
                    varitm10.Focus
                    varitm10.Click
                    'IE processing wait logic
                    Application.Wait (Now + TimeValue("00:00:03"))
                    While IE.Busy = True
                        DoEvents
                    Wend
                    
                    With IE
                        Do Until .readyState = 4: DoEvents: Loop
                        
                    End With
            'Selecting Procurement Link
            Set varitm11 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_LINKS_OPR_DEF_LINK_PM1")
                    varitm11.Focus
                    varitm11.Click
                    'IE processing wait logic
                    Application.Wait (Now + TimeValue("00:00:03"))
                            While IE.Busy = True
                                DoEvents
                            Wend
                            
                    With IE
                        Do Until .readyState = 4: DoEvents: Loop
                        
                    End With
            'clicking Sub-Procurement Link---Open POPUP Window
            Set varitm12 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_PM_WRK_OPR_DEF_APVCHR_PB")
                    varitm12.Focus
                    varitm12.Click
            Application.Wait (Now + TimeValue("00:00:03"))
                    While IE.Busy = True
                        DoEvents
                    Wend
                    
            With IE
                Do Until .readyState = 4: DoEvents: Loop
                
            End With
'Debug.Print IE.LocationName, IE.LocationURL, IE.AddressBar, IE.Application

           ' For Each IE In shell
            'Print URL for Each Window but only one URL is getting printed as POPUP window dont have URL associated, it is getting open from DO-Modal
            'sh.Cells(i + 7, 5).Value = IE.LocationURL
            'Exit For
            'Next

  For Each w In CreateObject("Shell.Application").Windows
    If w.Name Like "*Internet Explorer" Then
      Debug.Print w.LocationURL
    End If
  Next
'sh.Cells(10, 5).Value = IE.LocationName
'sh.Cells(11, 5).Value = IE.LocationURL
'sh.Cells(12, 5).Value = IE.AddressBar
'sh.Cells(13, 5).Value = IE.Application
'Set varitm13 = IE.document.getElementById("ptifrmtgtframe").contentWindow.document.all.Item("OPR_DEF_TBL_AP_PYMNT_RCRD_FLG")
'Set varitm13 = IE.document.getelementbyid("pt_modals").getelementbyid("ptMod_0").getelementbyid("ptModTable_0").getelementbyid("ptModContent_0").getelementbyid("ptModFrame_0").getelementbyid("OPR_DEFAULT").getelementbyid("win0divPAGECONTAINER").getelementbyid("win0divPSPAGECONTAINER").getelementbyid("ACE_width").getelementbyid("win0divOPR_DEF_TBL_AP_AUTH_APPROVE_VCHR").getelementbyid("ACE_OPR_DEF_TBL_AP_AUTH_APPROVE_VCHR").getelementbyid("win0divOPR_DEF_TBL_AP_ORIGIN").getelementbyid("OPR_DEF_TBL_AP_ORIGIN")
 'If iePopup Is Nothing Then
'Set iePopup = GetInstance(TimeOutInSeconds:=5, _
'URL:="11http://www.dowjones.com/DJCom/Images/ContentImages/TheCompany/virtuouscircle.jpg")
'End If
        
      '  varitm13.Focus
      '  varitm13.Click



Set varitm13 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.all.Item("#ICSave")
        varitm13.Focus
        varitm13.Click

Application.Wait (Now + TimeValue("00:00:03"))
        While IE.Busy = True
            DoEvents
        Wend
        
With IE
    Do Until .readyState = 4: DoEvents: Loop
    
End With

Set varitm14 = IE.document.getelementbyid("ptifrmtgtframe").contentWindow.document.getelementbyid("#ICList")
        varitm14.Focus
        varitm14.Click

Application.Wait (Now + TimeValue("00:00:03"))
        While IE.Busy = True
            DoEvents
        Wend
        
With IE
    Do Until .readyState = 4: DoEvents: Loop
    
End With
'IE.Navigate "https://fms-dev.intertek.com/psp/FINDEV1/EMPLOYEE/ERP/c/MAINTAIN_SECURITY.USERMAINT.GBL?FolderPath=PORTAL_ROOT_OBJECT.PT_PEOPLETOOLS.PT_SECURITY.PT_USER_PROFILES.PT_USERMAINT_GBL&IsFolder=false&IgnoreParamTempl=FolderPath%2cIsFolder"
sh.Cells(i, 2).Value = "Complete"
End If
End If

Next i


End Sub


Please suggest further.

Regards:
Aditya Jain


----------



## ZVI

aadityajain08 said:


> Thanks Zvi, I incorporated the code you provided but the "for" loop is getting executed only once and giving the output as the parent URL at immidiate window of VBE.


Can't provide the exact suggestion without debugging your code which is impossible to me because of unknown links login & password.
So just a guessing - it looks like the only single IE window is used for navigation to some web-pages.
If you see more than one IE window simultaneously then try commenting If-Then-EndIf lines to test all open IE windows, like this:


		Rich (BB code):
__


  Dim w As Object
  On Error Resume Next
  For Each w In CreateObject("Shell.Application").Windows
    'If w.Name Like "*Internet Explorer" Then
      Debug.Print w.Name
      Debug.Print w.LocationURL
    'End If
  Next


----------



## ZVI

If site uses frames then the same URL appears for different content.
In that case checking of a window title instead of URL can help:



		Rich (BB code):
__


  Dim w As Object
  On Error Resume Next
  For Each w In CreateObject("Shell.Application").Windows
    'If w.Name Like "*Internet Explorer" Then
      Debug.Print w.Document.Title
    'End If
  Next

Frame can be used for popup as well.
Then use: Set IE = w.Document.frames(0).Document 
where 1 can be used instead of 1


----------



## ZVI

ZVI said:


> Frame can be used for popup as well.
> Then use: Set IE = w.Document.frames(0).Document
> where 1 can be used instead of *0*


More correctly: Set IE = w.Document.frames(0)
where exact index or name of a frame can be used instead of the zero index.
After that something like this will work: IE.Document.getElementById("Submit").Click


----------



## RL101

Hi all,

I'm looking to create a VBA macro which will be ran from Excel (2003 or 2010) & which works with Internet Explorer. I have added 'Microsoft Internet Controls' to VBA References, and have looked at plenty of VBA code on the forum which opens & then navigates to specific websites. 

However, what I need is for this macro to affect an already open IE window.

Does anyone have an idea of the syntax / command to have excel "select" a specific IE window already open? 

Many thanks!


----------



## aadityajain08

Thanks Zvi for your efforts. I really sorry but i can not share the credentials and URL as it is client data and i need to adhere to the client data protection policy of my organization.
I applied the code w.r.t. frames #99 and Location URL #98. But in both cases 'for' loop gets executed only once. 
It seems system is treating it as a single window. When i applied code related to Frame then the title of parent window gets printed. Below is the HTML Code


		HTML:
__


<head>...</head>
****** class="PSPAGE" id="ptiframetemplate" style="cursor: auto;">
		<div id ="ptpopupmask" style="display: none;"></div>
		<div>...</div>
		<div id = "ptiframecontent">...</div>
		<div class = "ptalpagemask" id = "ptalpagemask"></div>
		<div class = "prcsmsgwindow" id = "NewProcessmsgwindow" style= "right: 0px; display: none;" ></div>
		<div id = "pt_modalmask" style= "width: 1384px; height: 580px; display: none;" ></div>
		<div id = "pt_modalmaskCover"></div>
		<div class = "PSMODAL" id = "pt_modals" style= "display: none; background-color: transparent" >...</div>
</body>


When i verify the element ID in parent window by pressing F12 and selecting field, it expands the 


		HTML:
__


<div id = "ptiframecontent">

. At this time, there is minimal data in


		HTML:
__


<div class = "PSMODAL">

division. However as soon as i click the link to open popup window, the data gets populated in 


		HTML:
__


<div class = "PSMODAL" id = "pt_modals" style= "display: none; background-color: transparent" >...</div>.

Is there any way by which i can share the screenshot with you in order to elaborate the scenarion.
This is much required for me as i am trying to introduce robotics in my project. Please help.

Regards;
Aditya jain


----------



## ZVI

If system threats it as a single window, then seems it is dynamic page and you need to parse its content.
My participation in this long thread is limited by what is in the title "VBA Macro For Already Open IE Window", which is not web page scraping itself.
And as for me there is no way to debug via screenshots, but may be someone has faced with a similar problem. 
To involve experts with the appropriate skills it is better to create new thread.
Hope you will find the solution, good luck!


----------



## aadityajain08

Thanks Zvi for your support on the issue. I am submitting the partial automation idea. In case i will receive the positive feedback, then i will indulge more. Thanks Again.

Regards:
Aditya jain


----------



## Ahiru

I don't understand, thats mean navigate manually?.  I have the same problem that sugaprasad,  I need replace the actually URL, that's because I have to choice an option ("button") in a menu, but that button doesn't have an id or a tag, but I can see that the "button" just redirects me to some other url. I don't need open another tab because that mean log-in every time. Can anyone help me??.. Hmm sorry for the mistakes but I'm still learning English.


----------



## Ahiru

sugaprasad said:


> Hi ZVI,
> 
> I am trying to replace the existing URL in the address bar of already opened IE window. So far this is my code.
> 
> 
> 
> 
> Code:
> __
> 
> 
> Sub Replace_URL()
> 
> Dim shellWins As ShellWindows
> Dim ie As InternetExplorer
> 
> 
> Set shellWins = New ShellWindows
> 
> 
> If shellWins.Count > 0 Then
> ' Get IE
> Set ie = shellWins.Item(0)
> Else
> ' Create IE
> Set ie = New InternetExplorer
> ie.Visible = True
> End If
> 
> 
> 
> ie.navigate "javascript: $find('ReportViewerControl').exportReport('EXCEL');"
> 
> 
> 
> 
> 
> 
> 
> 
> Set shellWins = Nothing
> Set ie = Nothing
> 
> 
> End Sub
> 
> Here its goes in to else part. But the navigate link is opening in a new tab. but i want this to replace the url in existing tab.
> Is this can be done. Please help me.





I have the same problem that sugaprasad, I need replace the actually URL, that's because I have to choice an option ("button") in a menu, but that button doesn't have an id or a tag, but I can see that the "button" just redirects me to some other url. I don't need open another tab because that mean log-in every time. Can anyone help me??.. Hmm sorry for the mistakes but I'm still learning English.


----------

