表单上的“更新”按钮的VBA代码

时间:2014-03-26 12:37:45

标签: sql vba ms-access access-vba

我的表单有一个未绑定的组合框(cboJack)和7个未绑定的文本字段(txtID,txtSwitch,txtPortNumber,txtVoiceVLAN,txtdataVLAN,txtCableNumber,txtcomments3)

每当我从组合框中选择一个选项时,7个文本字段将通过使用以下代码自动填充:

Private Sub cboJack_Change()
Me.txtID = Me.cboJack.Column(0)
Me.txtSwitch = Me.cboJack.Column(2)
Me.txtPortNumber = Me.cboJack.Column(3)
Me.txtVoiceVLAN = Me.cboJack.Column(4)
Me.txtdataVLAN = Me.cboJack.Column(5)
Me.txtCableNumber = Me.cboJack.Column(6)
Me.txtComments3 = Me.cboJack.Column(7)
End Sub

我在表单上创建了一个更新按钮,以便在我从组合框中选择值并且所有内容自动填充后,我可以编辑我想要的任何字段,然后按更新按钮保存所有内容。一些字段是数字字段,一些是文本字段。出于某种原因,我收到了语法错误。这是我的命令按钮的代码。

Private Sub cmdUpdate_Click()
Dim strSQL As String

strSQL = "UPDATE Switches SET Switch = '" & Me.txtSwitch & "', [Port Number] = " & Me.txtPortNumber & ", [Voice VLAN] = " & Me.txtVoiceVLAN & ", [Data VLAN] = " & Me.txtdataVLAN & ", [Cable Number] = " & Me.txtCableNumber & ", [Comments] = '" & Me.txtComments3 & "' WHERE Jack = '" & Me.cboJack & "'"

DoCmd.RunSQL (strSQL)
End Sub

数字类型列是,端口号,语音VLAN,DataVLAN和电缆号码。 ID是自动编号,其余是文本列。

我认为存在问题的原因是端口号,语音VLAN,数据VLAN和电缆号码中的某些字段没有任何值(某些值为空)

有关如何解决此问题的任何建议吗?

提前致谢。

2 个答案:

答案 0 :(得分:1)

是的,问题很可能是由非字符串元素中的Null值引起的。

以下是一个快速简便的解决方法:

strSQL = "UPDATE Switches SET Switch = '" & Me.txtSwitch & "', " & _
" [Port Number] = " & Nz(Me.txtPortNumber,"NULL") & ", " & _
" [Voice VLAN] = " & Nz(Me.txtVoiceVLAN,"NULL") & ", " & _
" [Data VLAN] = " & Nz(Me.txtdataVLAN,"NULL") & ", " & _
" [Cable Number] = " & Nz(Me.txtCableNumber,"NULL") & ", " & _
" [Comments] = '" & Me.txtComments3 & "' WHERE Jack = '" & Me.cboJack & "'"

所以你实际上用字符串[column] = , [column2] = ,替换空值(导致sql语句有语法错误,如:NULL

示例结果:[column] = NULL, [column2] = NULL,

编辑:使用IIf检查空字符串

strSQL = "UPDATE Switches SET Switch = '" & Me.txtSwitch & "', " & _
" [Port Number] = " & IIf(Len(Nz(Me.txtPortNumber)) = 0 , "NULL",Me.txtPortNumber) & ", " & _
" [Voice VLAN] = " & IIf(Len(Nz(Me.txtVoiceVLAN)) = 0 , "NULL", Me.txtVoiceVLAN) & ", " & _
" [Data VLAN] = " & IIf(Len(Nz(Me.txtdataVLAN)) = 0 , "NULL", Me.txtdataVLAN)& ", " & _
" [Cable Number] = " & IIf(Len(Nz(Me.txtCableNumber)) = 0 , "NULL", Me.txtCableNumber) & ", " & _
" [Comments] = '" & Me.txtComments3 & "' WHERE Jack = '" & Me.cboJack & "'"

答案 1 :(得分:0)

我建议您根本不使用SQL Update。除了Null问题之外,如果有人在其中一个数字字段中输入非数字字符,或者在注释中输入撇号,则更新也会失败。 (或者更糟糕的是:思考" SQL注入")

使用文本框和文本字段时,Access会使用Null快速替换空字符串。你可以要么反对它,要么只是"顺应潮流"并使用一种安全处理空字符串和撇号的方法,无需额外的工作。

这是我的代码:

Private Sub cmdUpdate_Click()
With CurrentDb.OpenRecordset("Switches")
    .FindFirst ("Jack = '" & cboJack & "'")
    If .NoMatch Then
        '' add a new record perhaps?
    Else
        .Edit
        .Fields("Switch") = txtSwitch
        .Fields("Port Number") = txtPortNumber
        .Fields("Voice VLAN") = txtVoiceVLAN
        .Fields("Data VLAN") = txtdataVLAN
        .Fields("Cable Number") = txtCableNumber
        .Fields("Comments") = txtComments3
        .Update
    End If
End With
End Sub