检查空白输入框并在 VBA 中发送适当的消息时出现问题

Issue with checking for blank input boxes and sending appropriate message in VBA

我在 VBA 中的代码有问题,无法正确检查空白字段并在该事件中给出适当的消息,我无法弄清楚我做错了什么。我的问题是,只有客户端名称空白字段检查器才真正起作用,其他的则什么都不做。这是我的代码示例。

'Error Handling
If (Me!ClientName) = "" Then
    MsgBox "Client Name cannot be blank"
    End

Else
    If IsNumeric(ClientName.Value) = True Then
        MsgBox "Client Name must be letters only."
        End
        Exit Sub
    End If
End If

If (Me!ClientDoB) = "" Then
    MsgBox "Client Date of Birth cannot be blank"
    End
End If

If (Me!ClientAdd) = "" Then
    MsgBox "Client Address cannot be blank"
    End
End If

If (Me!ClientCity) = "" Then
    MsgBox "Client City cannot be blank"
    End
Else
    If IsNumeric(ClientCity.Value) = True Then
        MsgBox "Client City must be letters only."
        End
        Exit Sub
    End If
End If

If (Me!ClientSt) = "" Then
    MsgBox "Client State cannot be blank"
    End
End If

If (Me!ClientZC) = "" Then
    MsgBox "Client Zip Code cannot be blank"
    End
Else
    If IsNumeric(ClientZC.Value) = False Then
        MsgBox "Client Zip Code must be numbers only."
        End
        Exit Sub
    End If
End If

考虑使用 if-elseif 结构,例如:

If Me.clientname & "" = "" Then
    MsgBox "Client Name cannot be blank"
ElseIf Me.clientname Like "*[!A-Za-z]*" Then
    MsgBox "Client Name must contain letters only."
ElseIf Me.clientdob & "" = "" Then
    MsgBox "Client Date of Birth cannot be blank"
ElseIf Me.clientadd & "" = "" Then
    MsgBox "Client Address cannot be blank"
ElseIf Me.clientcity & "" = "" Then
    MsgBox "Client City cannot be blank"
ElseIf Me.clientcity Like "*[!A-Za-z]*" Then
    MsgBox "Client City must contain letters only."
ElseIf Me.clientst & "" = "" Then
    MsgBox "Client State cannot be blank"
ElseIf Me.clientzc & "" = "" Then
    MsgBox "Client Zip Code cannot be blank"
ElseIf Me.clientzc Like "*[!0-9]*" Then
    MsgBox "Client Zip Code must be numbers only."
End If

这是因为在 MS Access 中,空白字段不一定是 NULL。要解决此问题,请改用 NZ 函数。它在像您这样的字段可以为空或 NULL 的情况下非常有用(MS Access 区分两者!!)。

If (Nz(Me!ClientAdd,"")) = "" Then
    MsgBox "Client Address cannot be blank"
    End
End If

这将检测空白和空值并为您提供您所描述的预期结果。 上面的"If Then Else"方案post不推荐用于你的场景。因为一旦它找到 "true" 场景,所有其他场景都将被忽略...... 您 post 编写的代码是要使用的正确代码(和方法)。只需使用 Nz(!yourfield, Value if Null) 函数包装您的字段。

希望对您有所帮助。