vba 检查未绑定控件是否具有值的正确方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1392917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 10:45:42  来源:igfitidea点击:

Proper way to check if an unbound control has a value

ms-accessvba

提问by Nick Dandoulakis

Simple scenario: a form and one text box (unbound), Text1.

简单的场景:一个表单和一个文本框(未绑定)Text1

If "" <> Text1 Then
    MsgBox "Not Empty"
End If

The above code works. The expression ""<> Text1evaluates to True if the text box contain characters.

上面的代码有效。""<> Text1如果文本框包含字符,则表达式的计算结果为 True。

The opposite doesn't work, regardless of the text box is empty or not:

反之则行不通,无论文本框是否为空:

If "" = Text1 Then  ' or alternatively, False = ("" <> Text1)
     MsgBox "Empty!"
End If

Can you clarify this issue?

你能澄清这个问题吗?

采纳答案by Fionnuala

The textbox is usually null if it does not contain anything, this is not the same as a zero length string (""). It can often be best to use:

如果文本框不包含任何内容,则它通常为 null,这与零长度字符串 ("") 不同。通常最好使用:

If Trim(Text1 & "") = vbNullString
   'Empty

This will be true if the textbox contains spaces, a zero length string or null.

如果文本框包含空格、零长度字符串或空值,则为真。

回答by Renaud Bompuis

Alternatively, I've got a small function that I find useful for checking that sort of thing when dealing with various variable types and I just want to know whether it's blank.

或者,我有一个小函数,我发现在处理各种变量类型时检查这类事情很有用,我只想知道它是否为blank

'-----------------------------------------------------------------------------'
' True if the argument is Nothing, Null, Empty, Missing or an empty string.   '
'-----------------------------------------------------------------------------'
Public Function IsBlank(arg As Variant) As Boolean
    Select Case VarType(arg)
        Case vbEmpty
            IsBlank = True
        Case vbNull
            IsBlank = True
        Case vbString
            IsBlank = (arg = vbNullString)
        Case vbObject
            IsBlank = (arg Is Nothing)
        Case Else
            IsBlank = IsMissing(arg)
        End Select
End Function

Just Made a blog posttoday about it too.

今天也刚刚发表了一篇关于它的博客文章

回答by Markus

I always use the function Nz (variable, valueIfNull)to check those kind of things. For example:

我总是使用函数 Nz (variable, valueIfNull)来检查这些事情。例如:

 if (Len(Nz(Me.txt1, "")) > 0) then
        'Me.txt1 does not contain a value
 end if

Or if I want to save a textbox's value to a recordset:

或者,如果我想将文本框的值保存到记录集:

rst!Name = Nz(Me.txtName, "No name given")