验证对象是否存在以及指定的属性或方法有效的过程称为绑定。 可以进行两次此验证过程:在编译时(早期绑定)或运行时(后期绑定)。 当您将对象变量声明为特定的数据类型时,您正在使用“早期绑定”,因此可以在编译时进行验证。 当声明通用对象数据类型的变量时,您正在使用后期绑定。 在这种情况下,VBA必须在执行任何VBA语句(包括对对象或其属性或方法之一的引用)的过程中找到并验证对象信息。 早期绑定和后期绑定之间的时间差异可能非常明显。 下面列出了一些早期绑定的示例:
- 昏暗的appAccess作为Access.Application
- 昏暗的appExcel作为Excel.Application
- 昏暗winExcel作为Excel.Window
- 昏暗winProject作为Project.Window
- 昏暗的chkBox作为复选框
- 昏暗的cboFinance作为ComboBox
- 昏暗的cht主要作为图表
- 昏暗的lstLookup作为ListBox
- 昏暗的pvtNew作为数据透视表
Dim rst As ADODB.Recordset, strName As String
'Early Binding. Declaring fld as ADODB.Field results in
'times that are around 7% of those measured declaring fld
'as Object. In the case of several hundred Records, the difference
'would not be significant, but in the case of several hundred
'thousand Records, the time difference would be enormous.
Dim fld As ADODB.Field
'Late Binding
'Dim fld As Object
Set rst = New ADODB.Recordset
Set rst.ActiveConnection = CurrentProject.Connection
rst.Source = "tblEmployee"
rst.CursorType = adOpenStatic
rst.Open
rst.MoveFirst
Set fld = rst.Fields(0)
Do While Not rst.EOF
strName = fld.Name
rst.MoveNext
Loop
rst.Close
Set fld = Nothing
Set rst = Nothing
在任何情况下,都尽可能使用最具体的对象类型声明一个变量。
对于访问控制,这意味着使用例如:
Dim cmd As CommandButton
代替:
Dim cmd As Control
或者,最糟糕的是:
Dim cmd As Object
From: https://bytes.com/topic/access/insights/688152-early-vs-late-binding