Buscar..


Introducción

Si usa los objetos en otras aplicaciones como parte de su aplicación de Visual Basic, es posible que desee establecer una referencia a las bibliotecas de objetos de esas aplicaciones. Esta documentación proporciona una lista, fuentes y ejemplos de cómo usar bibliotecas de diferentes softwares, como Windows Shell, Internet Explorer, XML HttpRequest y otros.

Sintaxis

  • expression.CreateObject (ObjectName)
  • expresión; Necesario. Una expresión que devuelve un objeto de aplicación.
  • Nombre del objeto; Cadena requerida. El nombre de clase del objeto a crear. Para obtener información acerca de los nombres de clase válidos, vea OLE Programmatic Identifiers.

Observaciones

Cuando una aplicación admite la automatización, Visual Basic puede acceder a los objetos que la aplicación expone. Use Visual Basic para manipular estos objetos invocando métodos en el objeto u obteniendo y configurando las propiedades del objeto.

Si usa los objetos en otras aplicaciones como parte de su aplicación de Visual Basic, es posible que desee establecer una referencia a las bibliotecas de objetos de esas aplicaciones. Antes de poder hacer eso, primero debe asegurarse de que la aplicación proporciona una biblioteca de objetos.

Le permite seleccionar los objetos de otra aplicación que desea que estén disponibles en su código configurando una referencia a la biblioteca de objetos de esa aplicación.

Crea un objeto de automatización de la clase especificada. Si la aplicación ya se está ejecutando, CreateObject creará una nueva instancia.

Expresiones regulares de VBScript

Set createVBScriptRegExObject = CreateObject("vbscript.RegExp")

Herramientas> Referencias> Expresiones regulares de Microsoft VBScript #. #
DLL asociado: VBScript.dll
Fuente: Internet Explorer 1.0 y 5.5

Código

Puede usar estas funciones para obtener resultados RegEx, concatenar todas las coincidencias (si son más de 1) en una cadena y mostrar el resultado en la celda de Excel.

Public Function getRegExResult(ByVal SourceString As String, Optional ByVal RegExPattern As String = "\d+", _
    Optional ByVal isGlobalSearch As Boolean = True, Optional ByVal isCaseSensitive As Boolean = False, Optional ByVal Delimiter As String = ";") As String
    
    Static RegExObject As Object
    If RegExObject Is Nothing Then
        Set RegExObject = createVBScriptRegExObject
    End If
    
    getRegExResult = removeLeadingDelimiter(concatObjectItems(getRegExMatches(RegExObject, SourceString, RegExPattern, isGlobalSearch, isCaseSensitive), Delimiter), Delimiter)
    
End Function

Private Function getRegExMatches(ByRef RegExObj As Object, _
    ByVal SourceString As String, ByVal RegExPattern As String, ByVal isGlobalSearch As Boolean, ByVal isCaseSensitive As Boolean) As Object

    With RegExObj
        .Global = isGlobalSearch
        .IgnoreCase = Not (isCaseSensitive) 'it is more user friendly to use positive meaning of argument, like isCaseSensitive, than to use negative IgnoreCase
        .Pattern = RegExPattern
        Set getRegExMatches = .Execute(SourceString)
    End With
    
End Function

Private Function concatObjectItems(ByRef Obj As Object, Optional ByVal DelimiterCustom As String = ";") As String
    Dim ObjElement As Variant
    For Each ObjElement In Obj
        concatObjectItems = concatObjectItems & DelimiterCustom & ObjElement.Value
    Next
End Function

Public Function removeLeadingDelimiter(ByVal SourceString As String, ByVal Delimiter As String) As String
    If Left$(SourceString, Len(Delimiter)) = Delimiter Then
        removeLeadingDelimiter = Mid$(SourceString, Len(Delimiter) + 1)
    End If
End Function

Private Function createVBScriptRegExObject() As Object
    Set createVBScriptRegExObject = CreateObject("vbscript.RegExp") 'ex.: createVBScriptRegExObject.Pattern
End Function

Objeto del sistema de archivos de secuencias de comandos

Set createScriptingFileSystemObject = CreateObject("Scripting.FileSystemObject")

Herramientas> Referencias> Microsoft Scripting Runtime
DLL asociado: ScrRun.dll
Fuente: Windows OS

Acceso a archivos de MSDN con FileSystemObject

El modelo de objeto de sistema de archivos (FSO) proporciona una herramienta basada en objetos para trabajar con carpetas y archivos. Le permite usar la sintaxis conocida de object.method con un rico conjunto de propiedades, métodos y eventos para procesar carpetas y archivos. También puede emplear las instrucciones y comandos tradicionales de Visual Basic.

El modelo FSO le da a su aplicación la capacidad de crear, alterar, mover y eliminar carpetas, o de determinar si y dónde existen carpetas particulares. También le permite obtener información sobre las carpetas, como sus nombres y la fecha en que se crearon o modificaron por última vez.

Temas de MSDN-FileSystemObject : " ... explica el concepto de FileSystemObject y cómo usarlo " . Exceltrick-FileSystemObject en VBA - Explicación
Scripting.FileSystemObject

Diccionario de secuencias de comandos objeto

Set dict = CreateObject("Scripting.Dictionary")

Herramientas> Referencias> Microsoft Scripting Runtime
DLL asociado: ScrRun.dll
Fuente: Windows OS

Objeto Scripting.Dictionary
MSDN-objeto del diccionario

Objeto de Internet Explorer

Set createInternetExplorerObject = CreateObject("InternetExplorer.Application")

Herramientas> Referencias> Controles de Internet de Microsoft
DLL asociado: ieframe.dll
Fuente: navegador de Internet Explorer

Objeto MSDN-InternetExplorer

Controla una instancia de Windows Internet Explorer a través de la automatización.

Miembros básicos de Internet Explorer Objec

El siguiente código debe introducir cómo funciona el objeto de IE y cómo manipularlo a través de VBA. Recomiendo pasar a través de él, de lo contrario podría fallar durante múltiples navegaciones.

Sub IEGetToKnow()
    Dim IE As InternetExplorer 'Reference to Microsoft Internet Controls
    Set IE = New InternetExplorer
    
    With IE
        .Visible = True 'Sets or gets a value that indicates whether the object is visible or hidden.
        
        'Navigation
        .Navigate2 "http://www.example.com" 'Navigates the browser to a location that might not be expressed as a URL, such as a PIDL for an entity in the Windows Shell namespace.
        Debug.Print .Busy 'Gets a value that indicates whether the object is engaged in a navigation or downloading operation.
        Debug.Print .ReadyState 'Gets the ready state of the object.
        .Navigate2 "http://www.example.com/2"
        .GoBack 'Navigates backward one item in the history list
        .GoForward 'Navigates forward one item in the history list.
        .GoHome 'Navigates to the current home or start page.
        .Stop 'Cancels a pending navigation or download, and stops dynamic page elements, such as background sounds and animations.
        .Refresh 'Reloads the file that is currently displayed in the object.
        
        Debug.Print .Silent 'Sets or gets a value that indicates whether the object can display dialog boxes.
        Debug.Print .Type 'Gets the user type name of the contained document object.
        
        Debug.Print .Top 'Sets or gets the coordinate of the top edge of the object.
        Debug.Print .Left 'Sets or gets the coordinate of the left edge of the object.
        Debug.Print .Height 'Sets or gets the height of the object.
        Debug.Print .Width 'Sets or gets the width of the object.
    End With
    
    IE.Quit 'close the application window
End Sub

Raspado web

Lo más común que se puede hacer con IE es raspar parte de la información de un sitio web, o completar un formulario de sitio web y enviar información. Vamos a ver cómo hacerlo.

Consideremos el código fuente de example.com :

<!doctype html>
<html>
    <head>
        <title>Example Domain</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <style ... </style> 
    </head>

    <body>
        <div>
            <h1>Example Domain</h1>
            <p>This domain is established to be used for illustrative examples in documents. You may use this
            domain in examples without prior coordination or asking for permission.</p>
            <p><a href="http://www.iana.org/domains/example">More information...</a></p>
        </div>
    </body>
</html>

Podemos usar el código como abajo para obtener y configurar información:

Sub IEWebScrape1()
    Dim IE As InternetExplorer 'Reference to Microsoft Internet Controls
    Set IE = New InternetExplorer
    
    With IE
        .Visible = True
        .Navigate2 "http://www.example.com"
        
        'we add a loop to be sure the website is loaded and ready.
        'Does not work consistently. Cannot be relied upon.
        Do While .Busy = True Or .ReadyState <> READYSTATE_COMPLETE 'Equivalent = .ReadyState <> 4
            ' DoEvents - worth considering. Know implications before you use it.
            Application.Wait (Now + TimeValue("00:00:01")) 'Wait 1 second, then check again.
        Loop
        
        'Print info in immediate window
        With .Document 'the source code HTML "below" the displayed page.
            Stop 'VBE Stop. Continue line by line to see what happens.
            Debug.Print .GetElementsByTagName("title")(0).innerHtml 'prints "Example Domain"
            Debug.Print .GetElementsByTagName("h1")(0).innerHtml 'prints "Example Domain"
            Debug.Print .GetElementsByTagName("p")(0).innerHtml 'prints "This domain is established..."
            Debug.Print .GetElementsByTagName("p")(1).innerHtml 'prints "<a href="http://www.iana.org/domains/example">More information...</a>"
            Debug.Print .GetElementsByTagName("p")(1).innerText 'prints "More information..."
            Debug.Print .GetElementsByTagName("a")(0).innerText 'prints "More information..."
            
            'We can change the localy displayed website. Don't worry about breaking the site.
            .GetElementsByTagName("title")(0).innerHtml = "Psst, scraping..."
            .GetElementsByTagName("h1")(0).innerHtml = "Let me try something fishy." 'You have just changed the local HTML of the site.
            .GetElementsByTagName("p")(0).innerHtml = "Lorem ipsum........... The End"
            .GetElementsByTagName("a")(0).innerText = "iana.org"
        End With '.document
        
        .Quit 'close the application window
    End With 'ie
    
End Sub

Que esta pasando? El jugador clave aquí es el .Documento , que es el código fuente HTML. Podemos aplicar algunas consultas para obtener las Colecciones u Objetos que deseamos.
Por ejemplo, el IE.Document.GetElementsByTagName("title")(0).innerHtml . GetElementsByTagName devuelve una colección de elementos HTML, que tienen la etiqueta " título ". Sólo hay una etiqueta de este tipo en el código fuente. La colección está basada en 0 Entonces para obtener el primer elemento agregamos (0) . Ahora, en nuestro caso, solo queremos el innerHtml (un String), no el Element Object en sí mismo. Por eso especificamos la propiedad que queremos.

Hacer clic

Para seguir un enlace en un sitio, podemos usar múltiples métodos:

Sub IEGoToPlaces()
    Dim IE As InternetExplorer 'Reference to Microsoft Internet Controls
    Set IE = New InternetExplorer
    
    With IE
        .Visible = True
        .Navigate2 "http://www.example.com"
        Stop 'VBE Stop. Continue line by line to see what happens.
        
        'Click
        .Document.GetElementsByTagName("a")(0).Click
        Stop 'VBE Stop.
        
        'Return Back
        .GoBack
        Stop 'VBE Stop.
        
        'Navigate using the href attribute in the <a> tag, or "link"
        .Navigate2 .Document.GetElementsByTagName("a")(0).href
        Stop 'VBE Stop.
        
        .Quit 'close the application window
    End With
End Sub

Biblioteca de objetos HTML de Microsoft o mejor amigo de IE

Para aprovechar al máximo el HTML que se carga en el IE, puede (o debería) usar otra Biblioteca, es decir, la Biblioteca de Objetos HTML de Microsoft . Más sobre esto en otro ejemplo.

Principales problemas de IE

El problema principal con IE es verificar que la página haya terminado de cargarse y esté lista para interactuar con ella. The Do While... Loop ayuda, pero no es confiable.

Además, el uso de IE solo para raspar el contenido HTML es OVERKILL. ¿Por qué? Debido a que el navegador está diseñado para navegar, es decir, mostrar la página web con todos los CSS, JavaScripts, imágenes, ventanas emergentes, etc. Si solo necesita los datos en bruto, considere un enfoque diferente. Por ejemplo, utilizando XML HTTPRequest . Más sobre esto en otro ejemplo.



Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow