vba excel中单维变量数组中的元素数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37124669/
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-08 10:24:16  来源:igfitidea点击:

Number of elements in a single dimension variant array in excel

excelexcel-vbavba

提问by IntegrateThis

Is This code correct for determining the number of elements in a single dimension variant array in Excel VBA. Supposing I have a variant array named Array1 with k elements.

此代码是否正确用于确定 Excel VBA 中单维变量数组中的元素数量。假设我有一个名为 Array1 的变体数组,其中包含 k 个元素。

Dim n as Integer
n = UBound(Array1)

回答by tigeravatar

To get an accurate count, you need to do UBound - LBound + 1. This is because arrays don't have to go from index 1 to n, they can start at basically any index you want. Here's an example where it goes from 3 to 7, which is a total of 5 elements (3, 4, 5, 6, and 7):

要获得准确的计数,您需要执行UBound - LBound + 1. 这是因为数组不必从索引 1 到 n,它们基本上可以从您想要的任何索引开始。这是一个从 3 到 7 的示例,总共有 5 个元素(3、4、5、6 和 7):

Sub tgr()

    Dim Array1(3 To 7) As Variant
    Dim lNumElements As Long

    lNumElements = UBound(Array1) - LBound(Array1) + 1
    MsgBox lNumElements

End Sub