I have an array that looks like this:
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
What I would like to do now is get the maximum value from all the values in string. Is there an easy way in VBA to fetch the max value from an array?
asked Jun 13, 2016 at 12:08
Frits VerstratenFrits Verstraten
2,0097 gold badges22 silver badges40 bronze badges
1
Is there an easy way in VBA to fetch the max value from an array?
Yes — if the values are numeric. You can use WorksheetFunction.Max
in VBA.
For strings — this won’t work.
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
answered Jun 13, 2016 at 12:26
Robin MackenzieRobin Mackenzie
18.3k7 gold badges38 silver badges54 bronze badges
1
Simple loop would do the trick
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
answered Jun 13, 2016 at 12:11
The easiest way to retrieve the maximum (I can think of) is iterating through the array and comparing the values. The following two functions do just that:
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
Note, that each time a string (text) array is passed to the function. Yet, one function is comparing strings (text) while the other is comparing numbers. The outcome is quite different!
The first function (comparing text) will return (with the above sample data) af
as the maximum, while the second function will only consider numbers and therefore returns 6
as the maximum.
answered Jun 13, 2016 at 12:22
RalphRalph
9,2444 gold badges32 silver badges42 bronze badges
Solution for Collection.
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
answered Oct 27, 2017 at 12:21
AnsAns
1,2021 gold badge23 silver badges51 bronze badges
all_angarsk, Вы меня не поняли. Я имел ввиду, что не нужно усложнять. Любой модуль/процедуру Вы легко отправите в экспорт на флэшку в формате *.bas. И так точно вытянете его оттуда в любом месте, на любом компе, в любой документ. А с модулем кнопки — тяжелее. Ну и с самой кнопкой — нарисуйте встроенными инстр-ми фигуру (или обьект WordArt) что Вам нравится, и назначьте ей нужную процедуру (правая кнопка > Назначить макрос (или как там у Вас по локализации)). Всего пару кликов. И практично, и веселее, и проще, а не унылая серость.
А про «…регулярные выражения…«. Что Вы имели ввиду? Я их там не вижу.
Добавлено через 25 минут
Кажется, я понял про регулярку. Смотрите, у Тoiai грамотный и лаконичный код. Лично я бы все-таки сгенерированный массив выгрузил на лист, чтоб было видно. I.e., после next я бы добавил строку:
[a1].resize(1, ubound(a)).value=a
Дальше он вызывает окно сообщения MsgBox, в котором использует фукции не VBA, а Excel — Min и Max. Поэтому его тяжелая жизнь заставила вызывать их такими фразами Application.Max(a), Application.Min(a)…
Кстати, что б, если не нужно, не выкладывать массив на лист, его тоже можно одним движение загнать в этот же MsgBox.
на сайте
http://msoffice.nm.ru/faq/macros/variables.htm#faq548
примеры посмотрел
Sub primer()
Dim iMassiv()
‘Здесь идёт заполнение массива некими данными
iMassiv = [a1:e10].Value
MsgBox Join(Application.Transpose(Application.Index(iMassiv, 0, 1)), vbNewLine), , «Первый столбец :»
‘или так
With Application
MsgBox Join(.Transpose(.Index(iMassiv, 0, 3)), _
Chr(10)), , «Третий столбец :»
End With
With WorksheetFunction
MsgBox Join(.Transpose(.Index(iMassiv, 0, 5)), _
Chr(13)), , «Пятый столбец :»
End With
Dim iAverage#, iMin#, iMax#, iSum#, iProduct
‘ For iCount = 1 To 100
‘ iMassiv(iCount) = Rnd * 1000
‘ Next
With Application
iAverage = .Average(iMassiv)
iMin = .Min(.Transpose(.Index(iMassiv, 0, 3)))
iMax = .Max(.Transpose(.Index(iMassiv, 0, 4)))
iSum = .Sum(iMassiv)
iProduct = .Product(iMassiv)
End With
End Sub
You can use the following basic syntax to calculate the max value in a range using VBA:
Sub MaxValue()
Range("D2") = WorksheetFunction.Max(Range("B2:B11"))
End Sub
This particular example calculates the max value in the range B2:B11 and assigns the result to cell D2.
If you would instead like to display the max value in a message box, you can use the following syntax:
Sub MaxValue()
'Create variable to store max value
Dim maxValue As Single
'Calculate max value in range
maxValue = WorksheetFunction.Max(Range("B2:B11"))
'Display the result
MsgBox "Max Value in Range: " & maxValue
End Sub
The following examples shows how to use each of these methods in practice with the following dataset in Excel that contains information about various basketball players:
Example 1: Calculate Max Value of Range Using VBA and Display Results in Cell
Suppose we would like to calculate the max value in the points column and output the results in a specific cell.
We can create the following macro to do so:
Sub MaxValue()
Range("D2") = WorksheetFunction.Max(Range("B2:B11"))
End Sub
When we run this macro, we receive the following output:
Notice that cell D2 contains a value of 43.
This tells us that the max value in the points column is 43.
Example 2: Calculate Max Value of Range Using VBA and Display Results in Message Box
Suppose we would instead like to calculate the max value in the points column and output the results in a message box.
We can create the following macro to do so:
Sub MaxValue()
'Create variable to store max value
Dim maxValue As Single
'Calculate max value in range
maxValue = WorksheetFunction.Max(Range("B2:B11"))
'Display the result
MsgBox "Max Value in Range: " & maxValue
End Sub
When we run this macro, we receive the following output:
The message box tells us that the max value in the range B2:B11 is 43.
Note that in this example we calculated the max value in the range B2:B11.
However, if you’d like to instead calculate the max value in an entire column you could type B:B instead.
This will calculate the max value in all of column B.
Additional Resources
The following tutorials explain how to perform other common tasks in VBA:
VBA: How to Calculate Average Value of Range
VBA: How to Count Number of Rows in Range
VBA: How to Sum Values in Range
How to write a visual basic program to find the maximum and minimum number from an array. How to Add and get the elements from an array in visual basic.
Find a Max and Min number from an array in the visual basic program is really simple. but before directly jump to code let’s see how to Add and retrieve elements from an array in visual basic.
Visual basic program to Add and Retrieve values from an array
Module Module1 Sub Main() 'Declaration an array Dim a(5), i As Integer 'Add numbers in array a(0) = 10 a(1) = 13 a(2) = 20 a(3) = 25 a(4) = 30 a(5) = 35 'Retrive the value from an array For i = 0 To a.Count - 1 Console.WriteLine(a(i)) Next Console.ReadLine() End Sub End Module
Vb library contains lots of predefined method to make the task easy for programmers and a.MAX and a.Min is used to find the maximum and minimum number from an array. Below is an example
Module Module1 Sub Main() 'Declaration an array Dim a(5), i, sum As Integer sum = 0 'Add numbers in array a(0) = 10 a(1) = 13 a(2) = 20 a(3) = 25 a(4) = 30 a(5) = 35 Console.WriteLine("Max Number is: " & a.Max) Console.WriteLine("Min Number is: " & a.Min) Console.ReadLine() End Sub End Module
Output:
Max Number is: 35
Min Number is: 10
Check out more related visual basic program with example
Vb program to find the sum of digit
Vb Program to create the multiplication table