我有一些VBA代码会根据表单更新表格。它工作得很好,除了我希望表只更新用户填写信息的地方。如果该文本框是空白的,请不要更新表中的该字段。以下是工作更新代码。以If query.Parameters("P1")...
开头的行是我尝试制作If
语句,尝试查找哪些文本框值为Null
然后忽略这些,但我不知道这是否均匀朝着正确的方向前进。
Private Sub Command133_Click()
'Update row for downtime
Dim dbsCurrent As Database
Set dbsCurrent = CurrentDb
', suffix, production_date, reason, downtime_minutes, comment ,'" & CInt(Me.Text118) & "','" & CDate(Me.Text126) & "','" & Me.Text121 & "','" & CDbl(Me.Text123) & "','" & Me.Text128 & "'
'dbsCurrent.Execute " INSERT INTO tbl_Downtime (production_date) SELECT #" & Me.Text126 & "# FROM tbl_Downtime As t WHERE t.ID = " & Me.Text135 & ";"
'dbsCurrent.Execute "UPDATE tbl_Downtime SET job = '" & Me.Text116 & "', suffix = '" & Me.Text118 & "', production_date = #" & Me.Text126 & "#, reason = '" & Me.Text121 & "', downtime_minutes = " & Me.Text123 & ", comment = '" & Me.Text128 & "', shift = '" & Me.Text144 & "' WHERE t.ID = " & Me.Text135 & ";"
Dim query As QueryDef
Dim sql As String
For Each query In CurrentDb.QueryDefs
If query.Name = "UpdateDowntime" Then
Exit For
End If
Next query
If query Is Nothing Then
sql = "parameters " & _
"P1 text, P2 text, P3 Date, P4 Text, P5 Number, P6 Text, P7 Text, P8 Number;" & _
"UPDATE [tbl_Downtime] " & _
"SET job = [P1], suffix = [P2], production_date = [P3], reason = [P4], downtime_minutes = [P5], comment = [P6], shift = [P7] " & _
"WHERE[tbl_Downtime].id = [P8]"
'"(job, suffix, production_date, reason, downtime_minutes, comment, shift) " & _
'" VALUES ([P1], [P2], [P3], [P4], [P5], [P6], [P7]) WHERE[tbl_Downtime].id = [P8]"
Set query = CurrentDb.CreateQueryDef("UpdateDowntime", sql)
End If
query.Parameters("P1").Value = Me.Text116
query.Parameters("P2").Value = Me.Text118
query.Parameters("P3").Value = Me.Text126
query.Parameters("P4").Value = Me.Text121
query.Parameters("P5").Value = Me.Text123
query.Parameters("P6").Value = Me.Text128
query.Parameters("P7").Value = Me.Text144
query.Parameters("P8").Value = Me.Text135
If query.Parameters("P1").Value = "" Then Set query.Parameters("P1").Value = job End If ' WHERE [tbl_Downtime].id = [P8] END
query.Execute
答案 0 :(得分:1)
空字符串与数据库中的空值不同,因此如果您希望它等于null(或默认值,如果存在),则需要将参数值更改为空。
您可以有条件地设置参数值,如下所示:
If textbox1.text <> "" then
query.Parameters("P1").Value = textbox1.text
End if
或者如果文本框为空,您可以编写一个函数来将参数设置为空:
Function NothingIfEmpty(value As String)
If value = "" Then
NothingIfEmpty = Nothing
Else
NothingIfEmpty = value
End If
End Function
并像这样使用它:
query.Parameters("P1").Value = NothingIfEmpty(textbox1.text)
query.Parameters("P2").Value = NothingIfEmpty(textbox2.text)
答案 1 :(得分:0)
你可以这样做:
"SET job = Nz([P1], job), suffix = Nz([P2], suffix), production_date = Nz([P3], production_date), reason = Nz([P4], reason), downtime_minutes = Nz([P5], downtime_minutes), comment = Nz([P6], comment), shift = Nz([P7], shift) " & _
"WHERE [tbl_Downtime].id = Nz([P8], -[id])"