如何在 Excel VBA 中将整数设为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4023354/
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 do I make an integer to null in Excel VBA?
提问by Arlen Beiler
I am trying to detect whether an integer was set, and if not, skip most of the code in the loop (using an if statement). Here is what I have so for.
我试图检测是否设置了整数,如果没有,则跳过循环中的大部分代码(使用 if 语句)。这就是我所拥有的。
Do While hws.Cells(r, 9).Value <> ""
On Error Resume Next
ar = Null
ar = aws.Range("A:A").Find(hws.Cells(r, 2).Value).Row
If Not IsNull(ar) Then
'work with ar'
End If
r = r + 1
Loop
However, when I run it, ar = Nullhas problems. It says "Invalid use of null".
但是,当我运行它时,ar = Null有问题。它说“无效使用空值”。
采纳答案by Fionnuala
Find returns a range:
Find 返回一个范围:
Dim rf As Range
With aws.Range("A:A")
Set rf = .Find(hws.Cells(r, 2).Value)
If Not rf Is Nothing Then
Debug.Print "Found : " & rf.Address
End If
End With
-- http://msdn.microsoft.com/en-us/library/aa195730(office.11).aspx
-- http://msdn.microsoft.com/en-us/library/aa195730(office.11).aspx
回答by Foole
Variables defined as Integer cannot be Null in VBA. You will have to find another way to do what you want. eg use a different data type or use a magic number to indicate null (eg -1).
在 VBA 中定义为 Integer 的变量不能为 Null。你将不得不找到另一种方式来做你想做的事。例如,使用不同的数据类型或使用幻数来指示空值(例如 -1)。
In your example code, either ar will be assigned a Long value (Range.Row is a Long) or it will throw an error.
在您的示例代码中,要么为 ar 分配一个 Long 值(Range.Row 是一个 Long),要么会引发错误。
回答by OlimilOops
just use a variant and isempty:
只需使用变体和isempty:
Dim i
If IsEmpty(i) Then MsgBox "IsEmpty"
i = 10
If IsEmpty(i) Then
MsgBox "IsEmpty"
Else
MsgBox "not Empty"
End If
i = Empty
If IsEmpty(i) Then MsgBox "IsEmpty"
'a kind of Nullable behaviour you only can get with a variant
'do you have integer?
Dim j as Integer
j = 0
If j = 0 Then MsgBox "j is 0"

