DAO Recordset与众多Dlookups

时间:2016-10-28 15:27:20

标签: database vba ms-access access-vba dao

我为小型企业创建了一个访问数据库。在这个DB中,我经常使用以下命令通过VBA基于关键字段自动填充一些文本框:

me.textboxvalue0.value = Nz(DLookup("VALUE0", "tblsomething", "lookedfield = '" & Me.keyfield.Value & "'"), "")  
me.textboxvalue1.value = Nz(DLookup("VALUE1", "tblsomething", "lookedfield = '" & Me.keyfield.Value & "'"), "")  
me.textboxvalue2.value = Nz(DLookup("VALUE2", "tblsomething", "lookedfield = '" & Me.keyfield.Value & "'"), "") 

这段代码重复了我所有可自动填写的文本框,范围从2到15个txtbox。 我的问题是: 打开DAO记录集并查找包含其所有字段的特定行是否更快,或者是否更快(执行时间)继续使用多个Dlookup来逐行按字段提取字段。

1 个答案:

答案 0 :(得分:3)

您可以使用以下格式的 OnCurrent 事件:

Dim rst As DAO.Recordset
Dim SQL As String

SQL = "Select * From tblSomething Where lookedfield = '" & Me!keyfield.Value & "'")
Set rst = CurrentDb.OpenRecordset(SQL)
If rst.RecordCount > 0 Then
    Me!textboxvalue0.Value = rst!VALUE0.Value
    Me!textboxvalue1.Value = rst!VALUE1.Value
    Me!textboxvalue2.Value = rst!VALUE2.Value
Else
    Me!textboxvalue0.Value = Null
    Me!textboxvalue1.Value = Null
    Me!textboxvalue2.Value = Null
End If
rst.Close

Set rst = Nothing