Dim Count As Integer, maxVal As Long
maxVal = Values(1)
For Count = 2 to UBound(values)
If Values(Count) > maxVal Then
maxVal = Values(Count)
End If
Next Count
Option Explicit
Public Sub InitialValues()
Dim strValues(1 To 3) As String
strValues(1) = 3
strValues(2) = "af"
strValues(3) = 6
Debug.Print GetMaxString(strValues)
Debug.Print GetMaxNumber(strValues)
End Sub
Public Function GetMaxString(ByRef strValues() As String) As String
Dim i As Long
For i = LBound(strValues) To UBound(strValues)
If GetMaxString < strValues(i) Then GetMaxString = strValues(i)
Next i
End Function
Public Function GetMaxNumber(ByRef strValues() As String) As Double
Dim i As Long
For i = LBound(strValues) To UBound(strValues)
If IsNumeric(strValues(i)) Then
If CDbl(strValues(i)) > GetMaxNumber Then GetMaxNumber = CDbl(strValues(i))
End If
Next i
End Function
Sub testColl()
Dim tempColl As Collection
Set tempColl = New Collection
tempColl.Add 57
tempColl.Add 10
tempColl.Add 15
tempColl.Add 100
tempColl.Add 8
Debug.Print largestNumber(tempColl, 2) 'prints 57
End Sub
Function largestNumber(inputColl As Collection, indexMax As Long)
Dim element As Variant
Dim result As Double
result = 0
Dim i As Long
Dim previousMax As Double
For i = 1 To indexMax
For Each element In inputColl
If i > 1 And element > result And element < previousMax Then
result = element
ElseIf i = 1 And element > result Then
result = element
End If
Next
previousMax = result
result = 0
Next
largestNumber = previousMax
End Function
Sub CreateArray()
Dim a(5, 5, 5)
Dim i As Integer, j As Integer, k As Integer
For i = 0 To 5
For j = 0 To 5
For k = 0 To 5
a(i, j, k) = (i + 1) * (j + 1) * (k + 1) & "a"
Next k
Next j
Next i
Debug.Print ArrayMax(a)
End Sub
Function ArrayMax(a)
Dim e As Variant
'Get first value
For Each e In a
ArrayMax = e
Exit For
Next e
For Each e In a
ArrayMax = IIf(e > ArrayMax, e, ArrayMax)
Next e
End Function
5条答案
按热度按时间wnrlj8wa1#
VBA中有没有简单的方法从数组中获取最大值?
是-如果值是数字。您可以在VBA中使用
WorksheetFunction.Max
。对于字符串-这行不通。
ldfqzlk82#
简单的循环就可以了
polkgigr3#
检索最大值的最简单方法(我能想到的)是遍历数组并比较值。下面两个函数就是这样做的:
注意,每次一个字符串(文本)数组被传递给函数。然而,一个函数是比较字符串(文本),而另一个是比较数字。结果完全不同!
第一个函数(比较文本)将返回(使用上述样本数据)
af
作为最大值,而第二个函数将只考虑数字,因此返回6
作为最大值。k5hmc34c4#
收集的解决方案。
pw9qyyiw5#
这将查找x维数组(甚至是范围(例如
debug.print ArrayMax(Range("A1:C4"))
))中的最大值,并将与数值或字符串值一起工作: