2016-06-13 14 views
2

から最大値を取得する:私は今、やりたい何私はこのようになりますアレー持つ配列

Dim values(1 To 3) As String 

values(1) = Sheets("risk_cat_2").Cells(4, 6).Value 
values(2) = Sheets("risk_cat_2").Cells(5, 6).Value 
values(3) = Sheets("risk_cat_2").Cells(6, 6).Value 

は、文字列のすべての値から最大値を取得することです。 VBAで配列から最大値をフェッチする簡単な方法はありますか?

+1

配列要素の型として 'Double'を使用できますか? – Bathsheba

答えて

1

単純なループはトリック

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 
2

に配列を反復処理し、値を比較している(私は考えることができる)最大値を取得するための最も簡単な方法だろう。次の2つの関数は、まさにそれを実行します。

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 

注意を、それぞれの時間は、文字列(テキスト)配列が関数に渡されていること。しかし、文字列(テキスト)を比較する関数と、数値を比較する関数があります。結果は全く異なります!

最初の関数(テキストの比較)は(上記のサンプルデータで)afを最大値として返し、2番目の関数は数値のみを考慮するので、最大値として6を返します。

3

VBAで配列から最大値を取得する簡単な方法はありますか?

はい - 値が数値の場合。 VBAでWorksheetFunction.Maxを使用できます。

文字列の場合 - これは機能しません。

Sub Test2() 
    Dim arr(1 To 3) As Long 

    arr(1) = 100 
    arr(2) = 200 
    arr(3) = 300 

    Debug.Print WorksheetFunction.Max(arr) 

End Sub 
+1

または 'WorksheetFunction.Max(Range(" E4:E6 ")。Value)'? – shahkalpesh

+0

はい、同じ原則で動作します。 –

0

解決のための解決策。

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 
関連する問題