Public Function setFormCtlDefValue(ByVal theForm As Form, _
ByVal TempTables As String, _
ByVal TempFieldsCtl As String, _
ByVal orderCtl As String, _
Optional TempWhereSql As String = "") As Boolean
'=========================================================================================
'-函数名称: setFormCtlDefValue
'-功能描述: 根据记录设置子窗体默认值
'-输入参数: 参数1:theForm 窗体名称
' 参数2:TempTables 表名称
' 参数3:orderCtl 排序字段
' 参数4:TempWhereSql 临时的where语句
'-返回参数: True 为设置成功,False 为设置失败
'-使用示例: setFormCtlDefValue Me, "表名称","字段1,字段2,字段3", "排序字段"
'-相关调用:
'-使用注意:必须引用ADO
'-兼 容 性:
'-参考资料:
'-作 者: cuxun
'-创建日期: 2008年6月9日
'========================================================================================
Dim Conn As ADODB.Connection
Dim abString() As String
'''用逗号分隔
Dim rst As New ADODB.Recordset
Dim strSQL As String
Dim i As Integer
setFormCtlDefValue = False
'如果窗体是新记录状态就退出函数
If Not theForm.NewRecord Then Exit Function
Set Conn = CurrentProject.Connection
If Right(TempFieldsCtl, 1) = "," Then TempFieldsCtl = Mid(TempFieldsCtl, 1, Len(TempFieldsCtl) - 1)
abString() = Split(TempFieldsCtl, ",")
If Len(TempWhereSql) > 0 Then TempWhereSql = " where " & TempWhereSql
strSQL = "Select top 1 " & TempFieldsCtl & " FROM " & TempTables & TempWhereSql & " orDER BY " & orderCtl & " desc;"
rst.Open strSQL, Conn, adOpenKeyset, adLockOptimistic
If Not rst.EOF Then
For i = 0 To UBound(abString)
theForm.Controls(abString(i)).DefaultValue = "'" & rst(i) & "'"
Next
Else: setFormCtlDefValue = False
Exit Function
End If
setFormCtlDefValue = True
rst.Close
Set rst = Nothing
Set Conn = Nothing
End Function
示例下载:http://www.accessoft.com/article-show.asp?id=2186