You can indeed use the function application.worksheetfunction.max(rng) as noted. To give a bit more complete answer, almost ANY Excel formula that’s available on the worksheet is available to use in the VBA code window via the application.worksheetfunction collection. This includes max, min, sumif, vlookup, etc.
This should give you the same on-screen description of the arguments involved in the function that you do when using the function on a worksheet. However, as another use noted, using application.max(range) does not give the same argument help. Also as same user noted, there’s a difference in error handling between using application.max(rng) and worksheetfunction.max(rng), you can see this in the comment below
As for a programming logic to determine a max value from a list of values, the basic logic is this:
max = 0 'set "inital" max
For Each rcell in rrng.cells 'loop through values
if rcell.value > max then 'if a value is larger than the old max,
max = rcell.value ' store it as the new max!
Next rcell
This will often work, but is missing a reference:
worksheets("Data").Cells(Count, 4)= Application.WorksheetFunction.Max _
( worksheets("Data").range( cells(m,1) ,cells(n,1) )
The text «cells» should be preceded by a reference to which worksheet the cells are on, I would write this:
worksheets("Data").Cells(Count, 4) = Application.WorksheetFunction.Max _
( worksheets("Data").range( worksheets("Data").cells(m,1) ,worksheets("Data").cells(n,1) )
This can also be written like this which is clearer:
with worksheets("Data")
.Cells(Count, 4) = Application.WorksheetFunction.Max _
( .range( .cells(m,1) ,.cells(n,1) )
End With
I hope this helps.
Harvey
What is Max Function in VBA?
Max Function is used to calculate the largest number. There are several numerical functions in excel which can be used to count the range, sum up the lot or to find the minimum or maximum value from the range of numbers. Max function is used to find the maximum value out of a range of values. It is an inbuilt function in Excel and categorized as the Max function. However, in VBA, there is no inbuilt function as Max to get the maximum value. Max function can be used in VBA Excel also. For the function argument (array, range, etc.), it can be either entered directly into the function or defined as variables to use instead.
Syntax:
=application.WorksheetFunction.max(arg1,arg2,arg3……………arg30)
Parameter or Arguments used in Max function are:
arg1……arg30: number 1 to number 30 from which the maximum number is to be inferred. It can be number, named ranges, arrays or reference to numbers.
Note:
- If the arguments contain no numbers, MAX returns 0 (zero).
- Arguments that have error values or text and cannot be translated into numbers will throw errors.
- Max function returns a numeric value.
How to Enable the Developers Tab?
Developer tab is mandatory on the Excel ribbon to start and write the VBA macro. Follow the below steps to enable the developer’s tab in Excel.
Step 1: Go to File.
Step 2: Click on Options.
Step 3: In a window opening up named Excel Options, click on Customize Ribbon to access the ribbon customization options.
Step 4: Here in the customization options, you can see the Developer(Custom) option. Checkmark it, so that it gets activated on the main ribbon of excel and can easily be accessed. Click OK after checking the Developer option.
Step 5: Click on the Developer tab and then click the Visual Basic (ALT +F11) icon.
VBA editor will appear.
How to Use Max Function in Excel VBA?
Below are the different examples to use Max function in Excel VBA:
You can download this VBA Max Excel Template here – VBA Max Excel Template
VBA Max – Example #1
Take four numbers 12, 25, 36, 45. Find out Max’s number by using the max function.
Code:
Sub AA() Dim A As Integer Dim B As Integer Dim C As Integer Dim D As Integer Dim result As Integer A = 12 B = 25 C = 36 D = 45 result = WorksheetFunction.Max(A, B, C, D) MsgBox result End Sub
Note:
- Mention the data type of the variables through dim.
- Assign numbers to variables.
Run the code by pressing the F5 key or by clicking on the Play Button. The result will be displayed in the message box.
VBA Max – Example #2
Take four numbers 15, 34, 50, 62. Find out max number by using the Max function.
Code:
Sub AA1() A = 15 B = 34 C = 50 D = 62 result = WorksheetFunction.Max(A, B, C, D) MsgBox result End Sub
Note:
- Here, we have directly assigned numbers to four different variables without mentioning their data type. The program automatically decides the data type.
- Used those variables in the formula and got the result in the message box.
Run the code by pressing the F5 key or by clicking on the Play Button. The result will be displayed in the message box.
VBA Max – Example #3
Find the maximum value from the range by using the Max function.
Code:
Function getmaxvalue(Maximum_range As Range) Dim i As Double For Each cell In Maximum_range If cell.Value > i Then i = cell.Value End If Next getmaxvalue = i End Function
Note:
- A function procedure in VBA code performs calculations and returns the result.
- It can have an optional return statement. It is required to return a value from a function.
- Before using the function we need to define that particular function.
Syntax:
Function functionname(parameter_list)
Statement 1
Statement 2
Statement 3
:
End Function
Here, the function keyword is followed by a unique function name e.g. getmaxvalue(args_1,…args_n) and may or may not carry the list of parameters with datatype e.g. Maximum_range As Range. It ends with the End Function which indicates the end of the function. Mention the data type of the variables through dim.
Calling a function:
To invoke a function call the function by using the function name e.g getmaxvalue(args_1,…args_n).
The result will be as given below.
VBA Max – Example #4
Find the maximum value from the range by using the Max function.
Code:
Function getmaxvalue(Maximum_range As Range) Dim i As Double For Each cell In Maximum_range If cell.Value > i Then i = cell.Value End If Next getmaxvalue = i End Function
Note:
- Maximum_range represents a range of cells passed from the excel sheet as a parameter.
- The variable i is declared as Double.
- The For loop is iterated. With each iteration, the, if condition checks whether the value read from the corresponding cell, is greater than i. If the condition evaluates true then cell value is assigned to i.
- When all the cells in the Maximum_range have been iterated, the maximum among those will be assigned to i.
- Finally, i is assigned to getmaxvalue and returned to the calling cell.
The result will be as given below.
Conclusion
VBA max function is used to find the maximum value from a range of numbers. A function procedure is required to perform calculations. Dim is used to define variables. End function is used to end the function. It performs the task very fast and accurate. Though it is not an inbuilt function in VBA excel, however, by using function procedure we can perform the max function in VBA excel.
Recommended Article
This is a guide to VBA MAX. Here we discuss how to use MAX function in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA Solver
- VBA IF Statements
- VBA Sort
- VBA While Loop
1 / 1 / 0 Регистрация: 04.05.2011 Сообщений: 32 |
|
1 |
|
Excel Максимальное значение13.05.2019, 13:38. Показов 29095. Ответов 16
Добрый день, даны два столбца дробных значений (А1:А47 и В1:В47), нужно, с помощью макроса, из столбца В найти максимальное значение, а затем найти в А соответствующее значение для В максимального и вывести эти числа на экран.
0 |
Kate_27 198 / 132 / 67 Регистрация: 27.03.2019 Сообщений: 288 |
||||
13.05.2019, 13:52 |
2 |
|||
Добрый день,
1 |
1 / 1 / 0 Регистрация: 04.05.2011 Сообщений: 32 |
|
13.05.2019, 14:06 [ТС] |
3 |
Только мне надо, чтобы значения были выведены в ячейку, например, в Д 2 и С 2
0 |
1 / 1 / 0 Регистрация: 04.05.2011 Сообщений: 32 |
|
13.05.2019, 14:12 [ТС] |
4 |
Kate_27, приложила файл
0 |
Kate_27 198 / 132 / 67 Регистрация: 27.03.2019 Сообщений: 288 |
||||
13.05.2019, 14:18 |
5 |
|||
лялячка,
Добавлено через 3 минуты
1 |
1 / 1 / 0 Регистрация: 04.05.2011 Сообщений: 32 |
|
13.05.2019, 14:37 [ТС] |
6 |
В ячейку Н2 поместить максимальное число из столбца в, а в G2 соотвествующее маскимальному числу в , число из столбца а. Вот как -то так . Спасибо!!!!!!!!!!!!!!
0 |
Kate_27 198 / 132 / 67 Регистрация: 27.03.2019 Сообщений: 288 |
||||
13.05.2019, 14:44 |
7 |
|||
лялячка, Я так понимаю 2 максимальных значений в Вашем случае быть не может? Тогда можно цикл переписать так:
0 |
1 / 1 / 0 Регистрация: 04.05.2011 Сообщений: 32 |
|
13.05.2019, 18:39 [ТС] |
8 |
Спасибо, сделала, как вы написали, но поняла, что максимумов несколько, и мне надо взять последнее, в условии прописала (6 строчка) >=b , выводит в ячейку н2 верное значение, однако в g2 выводит неверное число, пишет там сигма. И еще мне надо столбик в разделить на ячейку h2 и вывести эти числа в столбик д, и столбик а разделить на g2 и вывести результат в столбец с, тоже с помощью макроса, вроде начала делать, но походу не правильно. Посмотрите, пожалуйста.
0 |
198 / 132 / 67 Регистрация: 27.03.2019 Сообщений: 288 |
|
13.05.2019, 20:24 |
9 |
лялячка, давайте так.
0 |
лялячка 1 / 1 / 0 Регистрация: 04.05.2011 Сообщений: 32 |
||||||
14.05.2019, 09:11 [ТС] |
10 |
|||||
Добрый день, файл с макросом не прикладывается, прикладываю без макроса, есть два столбика: 1. Из столбца В, выбрать самый последний максимум (число, которое располагается в 31 строке) и вывести в ячейку Н2. 2. Из столбца А, взять число которое стоит напротив В максимального (число, которое тоже располагается в 31 строке но в столбце А) и поместить его в G2.
Вот что я прописала в макросе, он правильно выводит значение В, но в ячейке G2 он вывод слово эксп, а должно быть значение 0,22 Вложения
0 |
Vlad999 3835 / 2261 / 753 Регистрация: 02.11.2012 Сообщений: 5,959 |
||||
14.05.2019, 09:32 |
11 |
|||
Добавлено через 3 минуты
но в ячейке G2 он вывод слово эксп это по тому что текст всегда больше числа и условие Cells(i, 2) >= b выполняется в первой же строке.
0 |
198 / 132 / 67 Регистрация: 27.03.2019 Сообщений: 288 |
|
14.05.2019, 09:48 |
12 |
лялячка, а зачем Вы условие Cells(i, 2)= b заменили на Cells(i, 2) >= b. Отсюда у Вас ошибка и вышла. Добавлено через 3 минуты
0 |
1 / 1 / 0 Регистрация: 04.05.2011 Сообщений: 32 |
|
14.05.2019, 10:08 [ТС] |
13 |
Спасибо! Но теперь в G2 он мне 0 выдает(((((а надо 0,22
0 |
3835 / 2261 / 753 Регистрация: 02.11.2012 Сообщений: 5,959 |
|
14.05.2019, 10:19 |
14 |
любое утверждение желательно подкреплять файлом.
0 |
1 / 1 / 0 Регистрация: 04.05.2011 Сообщений: 32 |
|
14.05.2019, 10:35 [ТС] |
15 |
Приложила
0 |
3835 / 2261 / 753 Регистрация: 02.11.2012 Сообщений: 5,959 |
|
14.05.2019, 10:41 |
16 |
почитайте про тип переменных. Integer — это только целые числа, по этому 0,22 округлялось до 0.
0 |
1 / 1 / 0 Регистрация: 04.05.2011 Сообщений: 32 |
|
14.05.2019, 10:52 [ТС] |
17 |
Огромное спасибо! Все получилось!!!!)))))))
0 |
VBA — определение максимального значения в колонке |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |