将文本框的默认值设置为查询结果VBA



我发现本文将文本框的默认值设置为查询结果我正在尝试使用以下代码,但我一直遇到错误。查询的名称是maxnote,然后在查询中重新计时的字段是maxnote。

Public Function MaxNote()
       MaxNote = CurrentDb.OpenRecordset("MaxNote").Fields("MaxNote")
End Function

使用 dlookup 用于此类简单任务,并注意, defaultValue 是文本,并使用 nz 如果maxNote可以是 null

Me!YourTextbox.DefaultValue = Chr(34) & LTrim(Nz(Str(DLookup("MaxNote", "MaxNote")))) & Chr(34)
Public Function MaxNote()
    Dim rst As DAO.Recordset
    Set rst = CurrentDb.OpenRecordset("MaxNote") 
    rst.MoveFirst
    MaxNote = rst.Fields("MaxNote")
End Function

尝试一下,如果您喜欢首次开放,而不是dlookup

在这里,On Error Resume Next可以有用,因为错误表示空结果。

Public Function MaxNote() as Variant
       MaxNote = "" ' default return value for not records found. Can be NULL or 0 too
   On Error Resume Next ' if lookup fails code resumes next line, what is End Function (nothing happens)
       MaxNote = CurrentDb.OpenRecordset("MaxNote").Fields("MaxNote") ' fetch the field from first row of recordset (standard after .OpenRecordSet() ), if no results an error is raised, but function resumes next line of code, what ends the function and still with MaxNote = "", the value if no records are found
End Function

最新更新