Access VBA: If Form Value <> NULL then run query else, end if. - not doing anything
I have a piece of code that I've haphazardly written in order to run a query on_click of a form button.
Private Sub Command153_Click()
If Forms![form name1]![form name2]!Text143 <&开发者_高级运维gt; Null Then
DoCmd.OpenQuery "InsertGroup", acNormal, acEdit
Else
End If
End Sub
I haven't written a custom if before in VBA so I think I'm probably just getting this wrong as it is literally not doing anything (No errors or anything, I assume its just not running the query). I know that the query I'm calling in works fine as if I simply get the on_click to run the query without the if, I have no problems whatsoever. I'm also referencing the correct textbox and have tried this both with and without test data in the text box.
Any help is greatly appreciated!
Regards,
Andy.
The usual way is to say:
If IsNull(Forms![form name1]![form name2]!Text143) Then
I do not believe it is possible to get an empty string in an Access control, unless the value is coming from a database that allows zero-length strings. Furthermore, if you are testing for zero-length strings, you may as well cover all your bases and test for space-filled strings, so you may see in some cases:
If Trim(Forms![form name1]![form name2]!Text143 & vbNullString ) = vbNullString Then
You'd normally cover both null and empty string. The textbox is liable to have a value, not null which you will see if you breakpoint the code to examine the value
If Nz(Forms![form name1]![form name2]!Text143,"") <> "" Then ...
The above answers seem good and correct but it's worth explicitly noting that a comparison to null as you had written in your first code:
If Forms![form name1]![form name2]!Text143 <> Null Then....
Will always fail / be evaluated as false, even if your form names are null, as Null has no value to compare to. You must use IsNull(value)
or Not Isnull(value)
if you want to know if something is null.
As an alternative method or to cover more bases you can use nz(VariableName)
which returns a zero length string ""
(which is also the same as vbNullString
) if VariableName
is null. Combined in this way you can check for both a zero length string and a null value in a single operation:
If nz(VariableName) = vbNullString then
Debug.Print "The variable is Null or Zero-length"
End If
精彩评论