vba 如何检查变量是否有值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12109863/
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
How to check a variable if it have a value or not?
提问by Gulredy
I have a variable which contains a range value which is selected by the user.
我有一个变量,其中包含用户选择的范围值。
How can I check if it have a value or not?
如何检查它是否具有值?
I've tried these:
我试过这些:
If variable_name.Value = Empty then ....
If variable_name.Value = " " then ...
But these are only good when the variable contains data like text or numbers or whitespace.
但这些只有在变量包含文本、数字或空格等数据时才有用。
Any idea?
任何的想法?
回答by user3357963
Depends what you are testing.
取决于你在测试什么。
A range object or a cell value?
范围对象还是单元格值?
Sub test()
Dim rngObject As Range
Dim value As Variant
Set rngObject = Sheet1.Range("A1:D5")
If Not rngObject Is Nothing Then
'If not nothing then run this code
End If
value = rngObject.Cells(1, 1).value
If Not IsEmpty(value) Then
'if Not empty then run this code
End If
If value <> vbNullString Then
'if value is not nullstring then run this code
End If
End Sub