关于微软com object早期绑定和后期绑定的用法
给客户写追溯系统或者一般的打印程序,一般都会遇到客户需要导出或导入EXCEL数据的情况。
而我用的电脑一般是一种EXCEL环境,而客户用的电脑OFFICE版本从低到高各个版本都有。这样程序的兼容性就打了折扣。
为了解决这个问题,我需要不用通常的方式,先引用EXCEL类型库,而是程序里引用类型库,也就是所谓的后期绑定。
代码区别如下,我已经测试通过。
1,通常的做法,引用EXCEL类型库,早期绑定。
Early Binding
Sub EarlyBindingEx()
Dim oXLApp As Excel.Application
Dim oXLWb As Excel.Workbook
Dim oXLWs As Excel.Worksheet
'~~> Establish an EXCEL application object
On Error Resume Next
Set oXLApp = GetObject(, "Excel.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set oXLApp = New Excel.Application End If
Err.Clear On Error GoTo 0
'~~> Show Excel
oXLApp.Visible = True
'~~> Open files
Set oXLWb = oXLApp.Workbooks.Open("C:Sample.xlsx")
'~~> Set the relevant worksheet
Set oXLWs = oXLWb.Sheets(1)
'
'~~> Rest of your code
'End Sub2,后期绑定。
Late Binding
Sub LateBindingEx()
Dim oXLApp As Object
Dim oXLWb As Object, oXLWs As Object
'~~> Establish an EXCEL application object
On Error Resume Next
Set oXLApp = GetObject(, "Excel.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set oXLApp = CreateObject("Excel.Application")
End If
Err.Clear On Error GoTo 0
'~~> Show Excel
oXLApp.Visible = True
'~~> Open files
Set oXLWb = oXLApp.Workbooks.Open("C:Sample.xlsx")
'~~> Set the relevant worksheet
Set oXLWs = oXLWb.Sheets(1)
'
'~~> Rest of your code
'End Sub关于这个问题,微软也有相应的文章可以参考。
https://support.microsoft.com/en-us/kb/245115
早期绑定:
' Set reference to 'Microsoft Excel 8.0 Object Library' in
' the Project|References dialog (or Tools|References for VB4 or VBA).
' Declare the object as an early-bound object
Dim oExcel As Excel.Application
Set oExcel = CreateObject("Excel.Application")
' The Visible property is called via the v-table
oExcel.Visible = True后期绑定:
' No reference to a type library is needed to use late binding.
' As long as the object supports IDispatch, the method can
' be dynamically located and invoked at run-time.
' Declare the object as a late-bound object
Dim oExcel As Object
Set oExcel = CreateObject("Excel.Application")
' The Visible property is called via IDispatch
oExcel.Visible = True








