我有一个文本框,用户输入要更新/编辑的行的ID。当他们输入存在的ID时,我让它正常工作,但是当他们输入不存在的ID或者将它留空时我收到错误。
目标:
允许空白 - 如果用户将该字段留空,则需要擦除表单并让用户继续(不需要消息框)。
当ID无效时,通过消息框警告用户。
当前代码
Private Sub Text135_LostFocus()
If Me.Text135 = Nothing Then
MsgBox "Nothing entered into the ID field. Query will not run"
GoTo Last_Line:
Else
sql = "SELECT * FROM tbl_Downtime WHERE ID = " & Forms![DTForm]![Text135] & ";"
Set db = CurrentDb
Set rs = db.OpenRecordset(sql)
Me.Text126.Value = rs!production_date
Me.Text144.Value = rs!shift
Me.Text116.Value = rs!job
Me.Text118.Value = rs!suffix
Me.Text121.Value = rs!reason
Me.Text123.Value = rs!downtime_minutes
Me.Text4.Value = rs!people_missing
Me.Text128.Value = rs!comment
Set db = Nothing
Set rs = Nothing
Last_Line:
End If
End Sub
答案 0 :(得分:1)
当字段为空时,完全停止执行sub:
If Nz(Me.Text135) = "" Then 'Text135 is null or empty
Exit Sub
End If
但如果您问题中的代码是您的实际代码(而不仅仅是缩短的示例),那么您既不需要Exit Sub
也不需要GoTo Last_Line:
部分,因为之后在消息框中,代码执行将跳转到End If
。
检查Recordset是否包含任何行:
Set db = CurrentDb
Set rs = db.OpenRecordset(sql)
If rs.EOF Then
'rs.EOF is True when there are no rows
MsgBox "ID is not valid"
Else
'do stuff
End If
Set db = Nothing
Set rs = Nothing