Access 2016运行时错误无效使用null

时间:2018-10-12 18:15:14

标签: vba ms-access

我正在检查Access 2016表单中是否存在记录(如果存在),如果未将其添加到数据库,则显示一条消息。但是当txtRepGrpNumber为空时,我得到null的无效使用,如果不为空,即使数据库中已经存在它也会添加它。 RepGrpNumber是数据库中的一个数字字段。我的if陈述有误。

 Private Sub btnSave_Click()
Dim db As DAO.Database
Dim strSql As String
Dim message As String
Set db = CurrentDb
If Nz(CStr(Me.txtRepGrpNumber)) >= "" Then
strSql = "INSERT INTO dbo_TblSwShowRoom(RepGrpNumber, ViewOrder, RepCompany, AddressFull, Contact, Phone, Hours, ViewPhotos, ViewTour, ImageShow, Image, AddBy, DateAdded, DateChanged, ChangedBy, Enabled) " & _
         "VALUES('" & Me.txtRepGrpNumber & "','" & Me.txtViewOrder & "', '" & Me.txtRepCompany & "', '" & Me.txtAddressFull & "', '" & Me.txtContact & "', '" & Me.txtPhone & "', '" & Me.txtHours & "', '" & Me.txtViewPhotos & "', '" & Me.txtViewTour & "', '" & Me.txtImageShow & "', '" & Me.txtImage & "', '" & Me.txtAddBy & "', '" & Me.txtDateAdded & "', '" & Me.txtDateChanged & "', '" & txtChangedBy & "', '" & txtEnabled & "')"
    db.Execute strSql
    Me.SubFrmSwShowRoom.Requery
Else
    message = MsgBox("Cannot save because Group Number is Blank", vbCritical)
End If
'End If
Me.Requery
End Sub

3 个答案:

答案 0 :(得分:1)

{{1}}

答案 1 :(得分:1)

CStr无法转换Null值。 CStr(Null)引发与您相同的错误。应该这样做:

If Nz(Me.txtRepGrpNumber, vbNullString) <> vbNullString Then

答案 2 :(得分:0)

使用null无效的原因是,如果自打开表单以来txtRepGrpNumber的值未更改,并且该值为null,则CStr到达该字段时会抛出错误,错误使用null。

要修复它:

If Me.txtRepGrpNumber & vbNullString <> vbNullString Then