VBA/Excel/Access/Word/Excel/Binding — различия между версиями

Материал из VB Эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 16:33, 26 мая 2010

After the reference is set, Word variables can be declared with the correct (Word) variable type.

 
Sub WordEarlyBinding()
    Dim wdApp As Word.Application
    Dim wdDoc As Document
    Set wdApp = New Word.Application
    Set wdDoc = wdApp.Documents.Open(ThisWorkbook.Path & "\Word.docx")
    wdApp.Visible = True
    Set wdApp = Nothing
    Set wdDoc = Nothing
End Sub



An Example of Early Binding

 
Sub EarlyBinding()
    Dim objExcel As Excel.Application
    Set objExcel = New Excel.Application
    With objExcel
        .Visible = True
        .Workbooks.Add
        .Range("A1") = "Hello World"
    End With
End Sub



creates a new instance of Word and then opens and makes visible an existing Word document:

 
Sub WordLateBinding()
    Dim wdApp As Object, wdDoc As Object
    Set wdApp = CreateObject("Word.Application")
    Set wdDoc = wdApp.Documents.Open(ThisWorkbook.Path & "\Word.docx")
    wdApp.Visible = True
    Set wdApp = Nothing
    Set wdDoc = Nothing
End Sub



Creating and Referencing Objects

 
Sub UseGetObject()
    Dim wdDoc As Object
    Set wdDoc = GetObject(ThisWorkbook.Path & "\Word.docx")
    wdDoc.Application.Visible = True
    Set wdDoc = Nothing
End Sub



Early vs. Late Binding

 
Sub WordEarlyBound() 
    Dim wd As Word.Application 
    Dim doc As Word.Document 
    Set wd = New Word.Application 
    Set doc = wd.Documents.Add 
    doc.SaveAs "C:\testdoc1.doc" 
    doc.Close 
    Set doc = Nothing 
    Set wd = Nothing 
End Sub



If multiple versions of Word are installed, you can create an object for a specific version. The following statement, for example, uses Word 97.

 
Sub mate()
    Dim WordApp As Object
    Set WordApp = CreateObject("Word.Application.8")
End Sub



Late Binding

 
Sub late()
    Dim WordApp As Object
    Set WordApp = CreateObject("Word.Application")
End Sub



Using the CreateObject Function to Create a Late-Bound Instance of Excel

 
Sub LateBinding()
    "Declare a generic object variable
    Dim objExcel As Object
    "Point the object variable at an Excel application object
    Set objExcel = CreateObject("Excel.Application")
    "Set properties and execute methods of the object
    With objExcel
        .Visible = True
        .Workbooks.Add
        .Range("A1") = "Hello World"
    End With
End Sub