VBA 计算数组的非空元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17878095/
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
VBA count non empty elements of array
提问by karamell
Noob question: I want to count the non empty elements of an array?
菜鸟问题:我想计算数组的非空元素?
My attempt:
我的尝试:
Dim Arr(1 To 15) As Double
'populating some of the elements of Arr
'...
Dim nonEmptyElements As Integer, i As Integer
nonEmptyElements = 0: i = 0
For i = LBound(Arr) To UBound(Arr)
If Not Arr(i) = "" Then
nonEmptyElements = nonEmptyElements + 1
End If
Next
With this program I get the error: Type mismatch on If statement.
使用此程序,我收到错误消息:If 语句中的类型不匹配。
If try to change the if condition to If Not IsEmpty(Arr(i)) Then
and i get nonEmptyElements = 15
as a result.
如果尝试将 if 条件更改为If Not IsEmpty(Arr(i)) Then
,我会得到nonEmptyElements = 15
结果。
Any suggestions on how to complete the code?
关于如何完成代码的任何建议?
采纳答案by Ashneil Roy
Dim Arr(0 To 15) As Double
Arr(6) = 1.2
Arr(3) = 7
Dim nonEmptyElements As Integer, i As Integer
nonEmptyElements = 0 : i = 0
For i = LBound(Arr) To UBound(Arr)
If Not Arr(i) = 0 Then
nonEmptyElements = nonEmptyElements + 1
End If
Next
A double value by default is 0.0, so check if:
默认情况下双精度值为 0.0,因此请检查:
Arr(i) = 0
回答by alexkovelsky
Application.CountA(myarray)
CountA is a worksheet function for counting non-empty values.
CountA 是一个用于计算非空值的工作表函数。
Applies only to VBA6, does not work in VBA7.
仅适用于 VBA6,不适用于 VBA7。