code review vba – Acelere el procesamiento entre VBA e IE

Pregunta:

Estoy buscando acelerar el intercambio de vba a IE. Los Sendkeys funcionan, pero tenía curiosidad por saber si había una mejor manera de hacer esto.

El sitio al que se dirige es un formulario, pero no hay un botón de envío. La única forma de extraer los datos es pasar al siguiente cuadro o hacer clic en algún lugar de la pantalla. Sin embargo, esperaba tener todo esto automatizado a través de VBA.

¿Pensamientos?

Public Declare Function SetForegroundWindow Lib "user32" (ByVal HWND As Long) As Long

Function FillInternetForm()
Dim HWNDSrc As Long
Dim ie As Object

Set ie = CreateObject("InternetExplorer.Application")
    'create new instance of IE. use reference to return current open IE if
    'you want to use open IE window. Easiest way I know of is via title bar.

HWNDSrc = ie.HWND

ie.Navigate "http://helppointinfo.farmersinsurance.com/OCR/Labor_Rates/laborrates.asp"
    'go to web page listed inside quotes
ie.Visible = True
While ie.Busy
    DoEvents  'wait until IE is done loading page.
  Wend
ie.Document.getElementById("DirectZip").Value = Sheets("NAT").Range("C2").Value

SetForegroundWindow HWNDSrc

Application.SendKeys "{TAB 11}", True
DoEvents
Application.SendKeys "{NUMLOCK}", True

End Function

Public Sub RunRates()

Call FillInternetForm

End Sub

Respuesta:

Solo revisando lo que tienes aquí …

Sangría

El código se leería mucho mejor con la sangría adecuada:

Function FillInternetForm()
    Dim HWNDSrc As Long
    Dim ie As Object

    Set ie = CreateObject("InternetExplorer.Application")
    HWNDSrc = ie.HWND

    ie.Navigate "http://helppointinfo.farmersinsurance.com/OCR/Labor_Rates/laborrates.asp"
    ie.Visible = True
    While ie.Busy
        DoEvents  'wait until IE is done loading page.
    Wend
    ie.Document.getElementById("DirectZip").Value = Sheets("NAT").Range("C2").Value

    SetForegroundWindow HWNDSrc

    Application.SendKeys "{TAB 11}", True
    DoEvents
    Application.SendKeys "{NUMLOCK}", True

End Function

Public Sub RunRates()
    Call FillInternetForm
End Sub

Instrucción de Call

Como se respondió en esta pregunta de StackOverflow , la instrucción Call es una reliquia de versiones antiguas de VB, no es necesaria y, en mi opinión, solo agrega desorden.

Public Sub RunRates()
    FillInternetForm
End Sub

Acoplamiento

La función FillInternetForm se combina innecesariamente con el modelo de objetos de Excel – Sheets("NAT").Range("C2").Value debe pasarse como un parámetro de String a la función:

Function FillInternetForm(ByVal DirectZipValue As String)
    '...
    ie.Document.getElementById("DirectZip").Value = DirectZipValue
    '...
End Function

Public Sub RunRates()
    FillInternetForm Sheets("NAT").Range("C2").Value
End Sub

¿Función?

Las funciones VB son procedimientos con un valor de retorno. Si no se especifica, entonces está devolviendo una Variant ; aquí nunca se le asigna un valor de retorno a FillInternetForm , y lo que sea que esté devolviendo no se usará. En otras palabras, tiene un procedimiento ( Sub ), no una función . La firma debe modificarse así:

Public Sub FillInternetForm(ByVal DirectZipValue As String)

Me gustan las cosas explícitas: si un miembro va a ser Private , necesita un modificador de acceso Private ; si va a ser Public , no me gusta depender de los "valores predeterminados" de VB, principalmente porque codifico en diferentes idiomas donde estos valores predeterminados difieren (C #). Tener modificadores de acceso explícitos elimina la posible confusión, pero podría ser solo yo.

Por último, no entiendo por qué FillInternetForm tendría que presionar NUM LOCK , esto parece fuera de lugar y tiene un efecto secundario que podría sorprender a quien esté ejecutando ese código.

Leave a Comment

Your email address will not be published. Required fields are marked *

web tasarım