禁用与 Ms Access 中的窗体连接的所有控件



目前我使用列表框来选择表单提供编辑的记录。如果列表框中未选择任何记录,该怎么办?如何禁用和清空连接到表单数据源的所有控件?

您必须从表中取消绑定表单,并使用编码将值放入未绑定的表单控件中。在编程之前,有几件事需要设置。

  1. 确保所有表单控件名称都与表字段名称匹配。
  2. 确保表单属性中的记录源为空。
  3. 使用循环在选择列表框时"插入"查询中的值。

这需要更多的编程,因为您必须在每次控件更新时添加更新查询。但我发现这是最好的选择,因为它有助于防止损坏的记录,因为它在查看时不会绑定到记录。

当窗体打开时,所有内容都应为空,包括列表框。在列表框"更新后"事件中,放入编码以查询数据集并将值放入窗体控件中。

我没有您的表格字段的名称,也没有您的表单名称,所以我将使用随机名称。

编码示例:

Private sub Listbox1_AfterUpdate()
dim rst as dao.recordset
dim strSQL as string
dim ctr as control
for each ctr in me.controls
'Identifies if the control is a text box or combo box before trying to enter value in the incorrect control type
if ctr.controltype = actextbox or ctr.controltype = accombobox
strsql = "SELECT " & ctr.name & " as [FieldName] " & _
"FROM Table1 " & _
"WHERE (((Field1) ='" & me.listbox1 & "'));"
set rst = currentdb.openrecordset(strsql)
ctr.value = rst![FieldName]
rst.close
set rst = nothing
end if
next ctr
EndCode:
If not rst is nothing then
rst.close
set rst = nothing
end if
end sub

如果这对您不起作用,请告诉我,我们可以找出另一种解决方案。

假设这与你的另一个问题有关,你使用来自古斯塔夫的AfterUpdate-Event,你想禁用除ListBox之外的所有内容。

Private Sub Form_Load() ' same as ListBox_AfterUpdate, let you start with a new empty record assumin ID > 0
' Set filter.
Me.Filter = "[ID] = " & Nz(Me!NameOfYourListBox.value, 0) & ""
' Activate filter.
Me.FilterOn = True
End Sub
Private Sub Form_Current()
Dim ctl As Variant
Me.AllowAdditions = Me.NewRecord 'only allo new records at start
For Each ctl In Me.Controls
On Error Resume Next ' ignore errors because control has no enabled proptery
If ctl.Name <> "NameOfYourListBox" Then
ctl.Enabled = Not Me.NewRecord
End If
If Err.Number <> 438 And Err.Number <> 0 Then
' Error other than 438 should be handled
End If
On Error GoTo 0 'turn on errors again, if you use an error handler Goto ErrorHandlerName
Next
If Me.NewRecord Then
Me!ID.ControlSource = ""  'hide the {New} default text on new record
Else
Me!ID.ControlSource = "ID"
End If
End Sub

但是,如果没有必要从空表单开始,我建议使用子表单(与表单相同的记录源(进行编辑,无需任何代码即可同步到记录选择表单。

最新更新