IE 9 no acepta SendKeys
-
11-12-2019 - |
Pregunta
publiqué en IE 9 no acepta SendKeys para descargar un archivo, pero este problema está lo suficientemente separado de la respuesta que recibí como para justificar otra pregunta.Mi problema es que no consigo que IE 9 acepte ninguno de los SendKeys
.he intentado Página abajo, Pestaña, toda la F# llaves, y ninguna de ellas funciona.
Aquí está el código que estoy usando:
Dim ie As Object
'This creates the IE object
Sub initializeIE()
'call this subprocedure to start internet explorer up
Set ie = CreateObject("internetexplorer.application")
pos = 1
End Sub
'Initialize the class object
Private Sub Class_Initialize()
initializeIE
End Sub
Function followLinkByText(thetext As String) As Boolean
'clicks the first link that has the specified text
Dim alink As Variant
'Loops through every anchor in html document until specified text is found
' then clicks the link
For Each alink In ie.document.Links
If alink.innerHTML = thetext Then
alink.Click
'waitForLoad
Application.Wait Now + TimeValue("00:00:01")
Application.SendKeys "{PGDN}", True
Application.SendKeys "{PGUP}", True
'I've also tried calling it without Application before it
SendKeys "{F1}", True
SendKeys "{F2}", True
'Etc... Each of these not being received by IE 9
followLinkByText = True
Exit Function
End If
Next
End Function
Estoy totalmente perdido porque parece que la mayoría de los foros o tutoriales no hacen nada diferente para IE 9.El objeto IE se crea en un módulo de clase y se inicializa en el Class_Initialize
sub.No estoy seguro de si eso ayuda en algo, pero realmente no tengo idea de por qué esto no funciona y cualquier ayuda sobre cómo enviar claves a IE sería muy apreciada.
Solución
Esta es en realidad una copia de mi respuesta a esta pregunta, pero aún puede aplicarse.
¿Está activa la ventana de IE cuando intentas tu SendKeys
?Si no, esto explicaría que no funcione.
Para activar su ventana:
Al comienzo de su módulo, coloque esta línea de código:
Public Declare Function SetForegroundWindow Lib "user32" (ByVal HWND As Long) As Long
Esto le permitirá acceder a la SetForegroundWindow
función integrada en Windows.
En su código, mientras interactúa con su objeto IE, registre el HWND para esa ventana de esta manera:
Dim HWNDSrc As Long
HWNDSrc = ie.HWND
Luego, una vez que hayas cargado la página, usa esto para continuar y luego envía tus acciones clave:
SetForegroundWindow HWNDSrc
Sin embargo, esto puede no ser necesario, dependiendo de cómo interactúes con IE.En otras palabras, si no necesita ver/tocar la ventana (lo necesita para SendKeys
), aún puedes interactuar usando el objeto en el código.
Ahora, veo que estás usando la Aplicación. Espere después de hacer clic, pero eso no garantiza que la página de IE se haya cargado.Esta función debería ayudar con eso.
Public Sub WaitForIE(myIEwindow As InternetExplorer, HWND As Long, WaitTime As Integer)
' Add pauses/waits so that window action can actually
' begin AND finish before trying to read from myIEWindow.
' myIEWindow is the IE object currently in use
' HWND is the HWND for myIEWindow
' The above two variables are both used for redundancy/failsafe purposes.
' WaitTime is the amount of time (in seconds) to wait at each step below.
' This is variablized because some pages are known to take longer than
' others to load, and some pages with frames may be partially loaded,
' which can incorrectly return an READYSTATE_COMPLETE status, etc.
Dim OpenIETitle As SHDocVw.InternetExplorer
Application.Wait DateAdd("s", WaitTime, Now())
Do Until myIEwindow.ReadyState = READYSTATE_COMPLETE
' Wait until IE is done loading page and/or user actions are done.
Loop
Application.Wait DateAdd("s", WaitTime, Now())
While myIEwindow.Busy
DoEvents ' Wait until IE is done loading page and/or user actions are done.
Wend
On Error Resume Next
' Make sure our window still exists and was not closed for some reason...
For Each OpenIETitle In objShellWindows
If OpenIETitle.HWND = HWND Then
If Err.Number = 0 Then
Set myIEwindow = OpenIETitle
Exit For
Else
Err.Clear
End If
End If
Next OpenIETitle
On Error GoTo 0
End Sub
A riesgo de ser prolijo, actualicé su código con estas sugerencias...
' Added by Gaffi
Public Declare Function SetForegroundWindow Lib "user32" (ByVal HWND As Long) As Long
Dim HWNDSrc As Long
Dim ie As Object
'This creates the IE object
Sub initializeIE()
'call this subprocedure to start internet explorer up
Set ie = CreateObject("internetexplorer.application")
' Added by Gaffi
HWNDSrc = ie.HWND
pos = 1
End Sub
'Initialize the class object
Private Sub Class_Initialize()
initializeIE
End Sub
Function followLinkByText(thetext As String) As Boolean
'clicks the first link that has the specified text
Dim alink As Variant
'Loops through every anchor in html document until specified text is found
' then clicks the link
For Each alink In ie.document.Links
If alink.innerHTML = thetext Then
alink.Click
'waitForLoad
' Added by Gaffi
WaitForIE ie, HWNDSrc, 1
SetForegroundWindow HWNDSrc
'Application.Wait Now + TimeValue("00:00:01")
Application.SendKeys "{PGDN}", True
Application.SendKeys "{PGUP}", True
'I've also tried calling it without Application before it
SendKeys "{F1}", True
SendKeys "{F2}", True
'Etc... Each of these not being received by IE 9
followLinkByText = True
Exit Function
End If
Next
End Function