在编写代码时,您通常需要检索或设置应用程序中各种Forms,Reports,Controls或其他Objects的属性。 通常,使用以下语句来引用这些对象:
strCaption = Forms!("frmTest").cmdButton1.Caption
对于一个对象的单一引用,您无能为力以加快引用的速度。
另一方面,如果要在某种循环中引用该对象的许多属性,则可以通过将对象变量指向该对象并使用该变量来引用该对象来显着提高速度。宾语。
例如,如果您要引用许多特定控件的属性,则最好使用这样的代码,而不是每次都使用完整的语法来引用控件:
Dim ctl As CommandButton
Set ctl = Forms("frmTest").cmdButton1
Debug.Print ctl.Name
Debug.Print ctl.Width
'etc...
在另一个示例中,我将使用ADO Recordset中的特定字段来证明我的观点:
'This would be the slooooower case
Set rst = New ADODB.Recordset
Set rst.ActiveConnection = CurrentProject.Connection
rst.Source = "tblTests"
rst.Open
For intCounter = 1 to lngSomeReallyBigNumber
strName = rst.Fields(0).Name
Next intCounter
'The much faster procedure caches the reference to the Field, as such:
Set rst = New ADODB.Recordset
Set rst.ActiveConnection = CurrentProject.Connection
rst.Source = "tblTests"
rst.Open
Set fld = rst.Fields(0)
For intCounter = 1 to lngSomeReallyBigNumber
strName = fld.Name
Next intCounter
Even in this simple case, in which only a single dot was removed from within the expression, this faster code will take about 40% of the time it took in the slooooower version.
除了前面所述的以外,使用VBA的With..End With语法在代码执行时间上也有相同的改进。
最后,本技巧的关键点是:
对象引用中的点将始终降低代码速度。 您应该尽一切努力减少点数!From: https://bytes.com/topic/access/insights/712420-cache-object-references