Combobox null in if statement

烂漫一生 提交于 2019-12-05 01:20:58
HansUp

Nothing is ever equal to Null, not even another Null.

Use IsNull() to check whether the combo box is Null.

'If ProjectAddAllDueDateAutoCmBx = Null Then
If IsNull(ProjectAddAllDueDateAutoCmBx) = True Then

You cannot use a = Null comparison to get the results you want because Null propagates. To see this in action, try:

? Null = Null

in the Immediate Window and you'll see that Null is returned. Use the IsNull function, which will return true or false as you would expect.

Private Sub ProjectAddSetDateAutoBtn_Click()
If IsNull(ProjectAddAllDueDateAutoCmBx) Then
'Code1
Msgbox("ComboBox Is Null")
Else
'Code2
Msgbox("ComboBox Has Data")
End If
End Sub

While the accepted answer is totally correct, I use a different approach:

If HasValue(ProjectAddAllDueDateAutoCmBx) Then

where the HasValue function is:

Public Function HasValue(v As Variant) As Boolean
    If Trim(v & "") <> "" Then
        HasValue = True
    Else
        HasValue = False
    End If
End Function

This has the advantage of treating NULL and "" (or any pure whitespace) values the same, which is many times what you want with MSAccess controls. For example entering a value in a null-valued textbox and removing it again with backspace will result in a ""-value, not NULL. From a user-perspective this is mostly meant to be the same.

[The (v & "")-part is just a trick to force conversion to a string.]

I would suggest

If IsNull(ProjectAddAllDueDateAutoCmBx.Value) Then

It correctly checks for Null (IsNull instead of = Null), and it explicitly checks the value of the combo box.

(In most cases -- depending on the context -- just using the name of the control yields the value, but it doesn't hurt to be explicit.)

the equivalent of null in VB is Nothing so your check wants to be:

If ProjectAddAllDueDateAutoCmBx Is Nothing Then

....

it hope helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!