VBA/Excel/Access/Word/Excel/Binding
Содержание
- 1 After the reference is set, Word variables can be declared with the correct (Word) variable type.
- 2 An Example of Early Binding
- 3 creates a new instance of Word and then opens and makes visible an existing Word document:
- 4 Creating and Referencing Objects
- 5 Early vs. Late Binding
- 6 If multiple versions of Word are installed, you can create an object for a specific version. The following statement, for example, uses Word 97.
- 7 Late Binding
- 8 Using the CreateObject Function to Create a Late-Bound Instance of Excel
After the reference is set, Word variables can be declared with the correct (Word) variable type.
<source lang="vb">
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
</source>
An Example of Early Binding
<source lang="vb">
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
</source>
creates a new instance of Word and then opens and makes visible an existing Word document:
<source lang="vb">
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
</source>
Creating and Referencing Objects
<source lang="vb">
Sub UseGetObject()
Dim wdDoc As Object Set wdDoc = GetObject(ThisWorkbook.Path & "\Word.docx") wdDoc.Application.Visible = True Set wdDoc = Nothing
End Sub
</source>
Early vs. Late Binding
<source lang="vb">
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
</source>
If multiple versions of Word are installed, you can create an object for a specific version. The following statement, for example, uses Word 97.
<source lang="vb">
Sub mate()
Dim WordApp As Object Set WordApp = CreateObject("Word.Application.8")
End Sub
</source>
Late Binding
<source lang="vb">
Sub late()
Dim WordApp As Object Set WordApp = CreateObject("Word.Application")
End Sub
</source>
Using the CreateObject Function to Create a Late-Bound Instance of Excel
<source lang="vb">
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
</source>