我有一个保存的查询,qryInsertLog如下:
PARAMETERS UserIDPar Long, UnitIDPar Long, LogEntryPar LongText, FNotesPar LongText;
INSERT INTO tblLogBook ( UserID, UnitID, LogEntry, FNotes )
SELECT [UserIDPar] AS Expr1, [UnitIDPar] AS Expr2, [LogEntryPar] AS Expr3, [FNotesPar] AS Expr4;
我想在未绑定表单上单击保存按钮时尝试运行此查询,其中参数是从表单控件中收集的。我的保存按钮的VBA代码是:
Private Sub cmdSave_Click()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim okToSave As Boolean
If Me.cboUser.Value = 0 Or IsNull(Me.cboUser.Value) Then
MsgBox "You must choose a user. Record not saved."
okToSave = False
ElseIf Me.cboUnit.Value = 0 Or IsNull(Me.cboUnit.Value) Then
MsgBox "You must choose a unit. Record not saved."
okToSave = False
ElseIf Me.txtLogEntry.Value = "" Or IsNull(Me.txtLogEntry.Value) Then
MsgBox "You must have somtehing to log. Record not saved."
okToSave = False
Else
okToSave = True
End If
Set db = CurrentDb
Set qdf = db.QueryDefs("qryInsertLog")
qdf.Parameters("UserIDPar").Value = Me.cboUser.Value
qdf.Parameters("UnitIDPar").Value = Me.cboUnit.Value
qdf.Parameters("LogEntryPar").Value = Me.txtLogEntry.Value
qdf.Parameters("FNotesPar").Value = IIf(IsNull(Me.txtFNotes.Value), "", Me.txtFNotes.Value)
If okToSave Then
qdf.Execute
End If
qdf.Close
Set qdf = Nothing
End Sub
运行此代码时,表格的FNotes字段不会更新。其他三个字段按预期更新。 FNotes是唯一不需要的字段。我为FNotes参数编写了一个字符串,如下所示:
qdf.Parameters("FNotesPar").Value = "why doesn't this work"
而不是使用表单控件值,并得到相同的结果:该字段只是没有更新。当我从Access Objects窗口运行此查询并从提示中提供参数值时,它可以正常工作。当我创建绑定到表格的表单时,它似乎也可以正常工作。
我无法弄清楚为什么更新LogEntry字段没有问题,但FNotes字段无法更新。
答案 0 :(得分:1)
通过DAO.Recordset
而不是DAO.QueryDef
添加新记录。
首先,请包含此声明......
Dim rs As DAO.Recordset
然后在Set db = CurrentDb
....
Set rs = db.OpenRecordset("tblLogBook")
With rs
If okToSave Then
.AddNew
!UserID = Me.cboUser.Value
!UnitID = Me.cboUnit.Value
!LogEntry = Me.txtLogEntry.Value
!FNotes = Nz(Me.txtFNotes.Value, "")
.Update
End If
.Close
End With
注意Nz(Me.txtFNotes.Value, "")
为您提供与IIf(IsNull(Me.txtFNotes.Value), "", Me.txtFNotes.Value)
相同的内容,但更简洁。