2012-08-24 235 views
4

我有一个变量,它包含用户选择的范围值。如何检查变量是否有值?

我该如何检查它是否有价值?

我已经试过这些:

If variable_name.Value = Empty then .... 

If variable_name.Value = " " then ... 

但这些只是好当变量包含如文本或数字或空格的数据。

有什么想法?

+0

究竟是什么问题?你的代码何时失败,你想完成什么? – LittleBobbyTables

+0

我想完成的是“不良用户保护”。我想检查这个提到的变量是否有值。它在子程序中获得它的价值,该子程序旨在如果用户双击特定单元格在特定范围内进行选择。因为如果选择完成,用户按下一个按钮,然后导出选定的数据。所有这些工作正常,我只想检查按钮命中,如果该变量应该包含选择范围,是否包含它。通过这个,我可以警告用户在点击按钮之前做出选择! – Gulredy

+0

但是由上面的代码并不好,因为如果我将手表添加到保存范围的变量中,它将不写入任何值。甚至不是空的。它仍然包含范围。 我希望你明白我想说的是什么...... – Gulredy

回答

10

取决于您正在测试的内容。

范围对象或单元格值?

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