vba 检查数组的所有元素是否相同
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11968120/
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
Check to see if all the elements of an array are the same
提问by Kiran
I am not an expert in VBA, but I need to find if all the elements in an array are the same. Is there a function which we can use to check if all the elements are same?
我不是 VBA 专家,但我需要找出数组中的所有元素是否都相同。是否有一个函数可以用来检查所有元素是否相同?
回答by Gaffi
This is essentially the same as KopBuH's answer, but I prefer this method of looping/boolean assignment...
这基本上与KopBuH 的答案相同,但我更喜欢这种循环/布尔赋值的方法......
Function ElementsSame(arr As Variant) As Boolean
Dim l As Long
ElementsSame = True
For l = 1 To UBound(arr)
If arr(0) <> arr(l) Then
ElementsSame = False
Exit For
End If
Next l
End Function
回答by KopBuH
You can use this function to check any array of a variables of any type. If this function returns TRUE, it means all elements in array is equals.
您可以使用此函数检查任何类型的变量的任何数组。如果此函数返回 TRUE,则表示数组中的所有元素都相等。
Function IsAllElementsTheSame(arr As Variant) As Boolean
Dim buf As Variant
buf = arr(0)
Dim i As Integer
i = 0
Do While (buf = arr(i) And i < UBound(arr))
i = i + 1
Loop
IsAllElementsTheSame = False
If i = UBound(arr) And buf = arr(UBound(arr)) Then
IsAllElementsTheSame = True
End If
End Function