如果变量 IntVer 中有值,则此代码用于修改文本框。 IntVer 是包含文本框版本的变量。但是,如果用户从空文本框中启动add命令,则会出现类型不匹配错误。实际上这是一个SQL错误,因为它不能匹配字符串,因为 IntVer 不存在因此导致错误,因为它无法找到记录。
如何防止这种情况发生?我想添加recordcount <>0
会这样做,但SQL命令在recordcount之前执行。
因此错误对我有意义,我只是不知道如何解决它。
感谢您的帮助,
玛克辛
Private Sub cmdMod_Click()
Dim strSelSQL As String
strSelSQL = "SELECT EmpSWDetails.AssetID, EmpSWDetails.[" & SOFT & "] FROM EmpSWDetails " _
& "WHERE (((EmpSWDetails.AssetID)='" & Asset & "') AND ((EmpSWDetails.[" & SOFT & "])='" & IntVer & "'));"
Dim con As ADODB.Connection
Set con = Application.CurrentProject.Connection
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rs.Open strSelSQL, con, adOpenDynamic, adLockPessimistic
If rs.RecordCount <> 0 Then
rs.Fields(SOFT) = SELVER 'update version to new version
Else
rs!AssetID = Asset
rs.Fields(SOFT) = SELVER
End If
rs.Update
rs.Close
End Sub
答案 0 :(得分:1)
Nz()可能是你最好的选择,如果你只想捕获这个特定的错误(使用Nz将同时处理&#34; object = Null和object =&#34;&#34;同时制作if语句更短,更有效,更易读。)
Private Sub cmdMod_Click()
Dim strSelSQL As String
If Nz(intVer,"")="" then
msgbox "Please enter data.", vbOkOnly, "Required"
Else
strSelSQL = "SELECT EmpSWDetails.AssetID, EmpSWDetails.[" & SOFT & "] FROM EmpSWDetails " _
& "WHERE (((EmpSWDetails.AssetID)='" & Asset & "') AND ((EmpSWDetails.[" & SOFT & "])='" & IntVer & "'));"
<the rest of your code>
End If
End Sub
如果您希望它捕获所有错误,您可以实现错误处理程序。类似于以下内容
Private Sub cmdMod_Click()
Dim strSelSQL As String
On Error GoTo Error_Handler
<code>
Exit_Error_Handler:
Exit Sub
Error_Handler:
Msgbox "Error: " & Err.Number & vbCrLf & "Description: " & Err.Description
'You can also put code to handle specific errors
'For Example: If Err.Number = 13 Then Msgbox "Data required in Textbox", vbOkOnly, "Required" End If
GoTo Exit_Error_Handler
End Sub
Access中的错误处理是我唯一可以考虑使用GoTo语句的地方。