As the name suggests, Max is used to finding the maximum value from a given data set or array. Although it is a worksheet function, one may use it with the worksheet method as a worksheet function. However, there is a limitation to this method as this function takes an array as an argument. Therefore, there can only be 30 values in the array.
Excel VBA Max Function
We have several numerical functions in Excel. We can count numerical values in the range and sum and find the minimum value and maximum value of the lot. To find the maximum value of the lot, we have an excel function called MAXThe MAX Formula in Excel is used to calculate the maximum value from a set of data/array. It counts numbers but ignores empty cells, text, the logical values TRUE and FALSE, and text values.read more, which will return the maximum value of the supplied range of numbers. In VBA, we do not have any built-in function called “MAX” to get the maximum number. We will see how to use this Excel VBA Max function.
Table of contents
- Excel VBA Max Function
- Example of Max Function in Excel VBA
- Advanced Example of Max in Excel VBA
- Things to Remember
- Recommended Articles
Example of Max Function in Excel VBA
Unfortunately, we do not have the luxury of using MAX as the VBA built-in function, but we can access this function as a part of the Worksheet function class.
Now, look at the code below.
Code:
Sub MAX_Example1() Dim a As Integer Dim b As Integer Dim c As Integer Dim Result As Integer a = 50 b = 25 c = 60 Result = WorksheetFunction.Max(a, b, c) MsgBox Result End Sub
We have declared three variables to store the number in the above example.
Dim a As Integer Dim b As Integer Dim c As Integer
We have declared one more variable to show the results.
Dim Result As Integer.
For the first 3 three variables, we assigned values like 50, 25, and 60, respectively.
a = 50 b = 25 c = 60
In the next line, we have applied the MAX as a VBA worksheet functionThe worksheet function in VBA is used when we need to refer to a specific worksheet. When we create a module, the code runs in the currently active sheet of the workbook, but we can use the worksheet function to run the code in a particular worksheet.read more class to store the result to the variable “Result.”
Result = WorksheetFunction.Max(a, b, c)
So finally, we are showing the value in the message box in VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.
MsgBox Result
We will run this code using F5 or manually and see the result in the message box.
So, the result is 60.
From all the supplied numbers: 50, 25, and 60, the maximum number is 60.
Advanced Example of Max in Excel VBA
Loops are crucial in VBA to run through all the cells and arrive at the result. We will see how to combine VBA MAX with loops to arrive at the maximum value from the list of numbers.
We have a list of items and the monthly sales performance of those items, as shown below.
Now for each item, we want to know the maximum sale number across four months, as shown in the picture.
By applying MAX to Excel, we can find this in a few seconds.
We will now see how to find the maximum value using the VBA code.
The below code will perform the task of finding the maximum number for each item.
Code:
Sub MAX_Example2() Dim k As Integer For k = 2 To 9 Cells(k, 7).Value = WorksheetFunction.Max(Range("A" & k & ":" & "E" & k)) Next k End Sub
It will identify the maximum number easily.
Run the code manually or press the F5 key to see the result below.
To get the maximum values month name, use the below code.
Code:
Sub MAX_Example2() Dim k As Integer For k = 2 To 9 Cells(k, 7).Value = WorksheetFunction.Max(Range("B" & k & ":" & "E" & k)) Cells(k, 8).Value = WorksheetFunction.Index(Range("B1:E1"), WorksheetFunction.Match _ (Cells(k, 7).Value, Range("B" & k & ":" & "E" & k))) Next k End Sub
Based on the value provided by the VBA max function, the INDEX functionThe INDEX function in Excel helps extract the value of a cell, which is within a specified array (range) and, at the intersection of the stated row and column numbers.read more & MATCH functionThe MATCH function looks for a specific value and returns its relative position in a given range of cells. The output is the first position found for the given value. Being a lookup and reference function, it works for both an exact and approximate match. For example, if the range A11:A15 consists of the numbers 2, 9, 8, 14, 32, the formula “MATCH(8,A11:A15,0)” returns 3. This is because the number 8 is at the third position.
read more will return the associated month in the next line.
Things to Remember
- If their duplicate number is there, it will show only one number which comes first.
- It is the opposite formula of the MIN function in excelIn Excel, the MIN function is categorized as a statistical function. It finds and returns the minimum value from a given set of data/array.read more.
- The MAX function is not a VBA function. However, it is a built-in function in Excel, so use the worksheet function class.
You can download this Excel Template here – VBA Max Function Template.
Recommended Articles
This article has been a guide to VBA Max. Here, we learn how to use the Max function in VBA to find the maximum value from a supplied range of numbers, along with examples and downloadable codes. Below are some useful Excel articles related to VBA: –
- VBA FileCopy
- VBA Debug Print
- VBA FileSystemObject
- ByRef in VBA
- VBA Find and Replace
VBA — определение максимального значения в колонке |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
Teklan Пользователь Сообщений: 49 |
#1 28.03.2013 04:15:39 Доброй ночи, Предположим по примеру для X=1 X=5 необходимо найти максимальное число из столбика RESULT (равно 2). Потом для X=5 X=9 и т.д. Я делал при помощи поиска определяя номер строки для X из столбика Length и дальше определив регион для RESULT нахожу максимальное число. В приложение сам пример и ниже код.
Прикрепленные файлы
|
||
anvg Пользователь Сообщений: 11878 Excel 2016, 365 |
А можно по подробнее, что собственно говоря ищется? |
Johny Пользователь Сообщений: 2737 |
#3 28.03.2013 07:54:22
Уверены? Не вводите в заблуждение человека. Почитайте про параметр SearchDirection. There is no knowledge that is not power |
||
anvg Пользователь Сообщений: 11878 Excel 2016, 365 |
Johny |
Johny Пользователь Сообщений: 2737 |
#5 28.03.2013 08:35:42
Поясняю. There is no knowledge that is not power |
||
ber$erk Пользователь Сообщений: 2735 |
Teklan, Вы пишите, что «…Изходя из столбика X необходимо найти максимальное число из столбика RESULT…» Учимся сами и помогаем другим… |
Teklan Пользователь Сообщений: 49 |
#7 28.03.2013 10:43:31 Всем доброе утро. П.С. Средствами Excel будет как-то так (но надо на VBA чтобы «впилить» в общий расчет, но дико тормозит):
Прикрепленные файлы
Изменено: Teklan — 28.03.2013 10:46:23 |
||
anvg Пользователь Сообщений: 11878 Excel 2016, 365 |
#8 28.03.2013 11:14:23
Тогда так
Только тогда зачем используется Out As Integer в параметрах? |
||||
Teklan Пользователь Сообщений: 49 |
anvg, Сейчас попробую Ваш вариант. |
Казанский Пользователь Сообщений: 8839 |
#10 28.03.2013 11:40:26 ИМХО так быстрее:
Можете этот же принцип использовать в VBA. |
||
Казанский Пользователь Сообщений: 8839 |
#11 28.03.2013 11:43:24
Для этого вместо МАКС используйте НАИБОЛЬШИЙ с соотв. параметром. |
||
Teklan Пользователь Сообщений: 49 |
Казанский, спасибо. Постараюсь запомнить =) |
Казанский Пользователь Сообщений: 8839 |
#13 28.03.2013 12:13:07
На 2000 — наверно, на 200 тысяч — будет жестоко тормозить. Изменено: Казанский — 28.03.2013 12:14:47 |
||
vikttur Пользователь Сообщений: 47199 |
#14 28.03.2013 21:17:44 OFF
По тeklan‘ски — то не так, как думает Казанский |
||
ZVI Пользователь Сообщений: 4328 |
#15 28.03.2013 22:13:00
Вообще-то, со второй
Изменено: ZVI — 28.03.2013 22:13:40 |
||||
anvg Пользователь Сообщений: 11878 Excel 2016, 365 |
#16 29.03.2013 02:43:18 ZVI
Плюс шаг, другой вверх/вниз в зависимости от значения в xData(idBegin, 1). Для поиска половинным делением для 200000 потребуется до 17 операций поиска (правда, не учитывая, что VBA всё же интерпретатор) Изменено: anvg — 29.03.2013 03:10:21 |
||
galina mur Пользователь Сообщений: 245 |
#17 29.03.2013 13:26:51 не знаю,сколько строк всего прилагаю свой вариант
|
|
Teklan Пользователь Сообщений: 49 |
#18 31.03.2013 02:40:47 Спасибо всем за советы. |
- Что такое Max Function в VBA?
Что такое Max Function в VBA?
Макс функция используется для расчета наибольшего числа. В Excel есть несколько числовых функций, которые можно использовать для подсчета диапазона, суммирования лота или для поиска минимального или максимального значения из диапазона чисел. Функция Max используется для поиска максимального значения из диапазона значений. Это встроенная функция в Excel, которая относится к категории Max. Однако в VBA нет встроенной функции как Max, чтобы получить максимальное значение. Функция Max также может использоваться в VBA Excel. Для аргумента функции (массив, диапазон и т. Д.) Его можно либо ввести непосредственно в функцию, либо определить как переменные для использования вместо него.
Синтаксис:
=application.WorksheetFunction.max(arg1, arg2, arg3……………arg30)
Параметр или аргументы, используемые в функции Max:
arg1 …… arg30: число 1 — число 30, из которого следует вывести максимальное число. Это может быть число, именованные диапазоны, массивы или ссылки на числа.
Замечания:
- Если аргументы не содержат чисел, MAX возвращает 0 (ноль).
- Аргументы, которые имеют значения ошибок или текст и не могут быть переведены в числа, приведут к ошибкам.
- Функция Max возвращает числовое значение.
Как включить вкладку «Разработчики»?
Вкладка «Разработчик» обязательна на ленте Excel для запуска и записи макроса VBA. Выполните следующие шаги, чтобы включить вкладку разработчика в Excel.
Шаг 1: Перейти к файлу .
Шаг 2: Нажмите на Опции .
Шаг 3. В открывшемся окне с именем «Параметры Excel» нажмите «Настроить ленту», чтобы получить доступ к параметрам настройки ленты.
Шаг 4: Здесь в опциях настройки вы можете увидеть опцию Разработчик (Custom) . Отметьте его, чтобы он активировался на главной ленте Excel и был легко доступен. Нажмите OK после проверки опции Разработчик.
Шаг 5. Откройте вкладку « Разработчик » и щелкните значок Visual Basic (ALT + F11).
VBA редактор появится.
Как использовать функцию Max в Excel VBA?
Ниже приведены различные примеры использования функции Max в Excel VBA:
Вы можете скачать этот шаблон VBA Max Excel здесь — Шаблон VBA Max Excel
VBA Max — Пример № 1
Возьмите четыре числа 12, 25, 36, 45. Узнайте число Макса, используя функцию max.
Код:
Sub AA () Dim A как целое число Dim B как целое число Dim C как целое число Dim D как целое число Dim результат как целое число A = 12 B = 25 C = 36 D = 45 result = WorksheetFunction.Max (A, B, C, D) MsgBox результат End Sub
Замечания:
- Упомяните тип данных переменных через dim .
- Присвойте числа переменным.
Запустите код, нажав клавишу F5 или нажав кнопку воспроизведения. Результат будет отображен в окне сообщения.
VBA Max — Пример № 2
Возьмите четыре числа 15, 34, 50, 62. Узнайте максимальное число, используя функцию Max.
Код:
Sub AA1 () A = 15 B = 34 C = 50 D = 62 результат = WorksheetFunction.Max (A, B, C, D) MsgBox результат End Sub
Замечания:
- Здесь мы прямо присвоили номера четырем различным переменным, не упоминая их тип данных. Программа автоматически решает тип данных.
- Использовали эти переменные в формуле и получили результат в окне сообщения.
Запустите код, нажав клавишу F5 или нажав кнопку воспроизведения. Результат будет отображен в окне сообщения.
VBA Max — Пример № 3
Найдите максимальное значение из диапазона, используя функцию Max.
Код:
Функция getmaxvalue (Maximum_range As Range) Dim i As Double для каждой ячейки в Maximum_range If cell.Value> i Тогда i = cell.Value End If Next getmaxvalue = i End Function
Замечания:
- Функциональная процедура в коде VBA выполняет вычисления и возвращает результат.
- Он может иметь необязательный оператор возврата. Требуется вернуть значение из функции.
- Перед использованием функции нам нужно определить эту конкретную функцию.
Синтаксис:
Function functionname(parameter_list)
Statement 1
Statement 2
Statement 3
:
End Function
Здесь за ключевым словом функции следует уникальное имя функции, например, getmaxvalue (args_1, … args_n), и может содержать или не содержать список параметров с типом данных, например Maximum_range As Range. Он заканчивается функцией завершения, которая указывает конец функции. Упомяните тип данных переменных через dim .
Вызов функции:
Чтобы вызвать функцию, вызовите функцию, используя имя функции, например, getmaxvalue (args_1, … args_n) .
Результат будет таким, как указано ниже.
VBA Max — Пример № 4
Найдите максимальное значение из диапазона, используя функцию Max.
Код:
Функция getmaxvalue (Maximum_range As Range) Dim i As Double для каждой ячейки в Maximum_range If cell.Value> i Тогда i = cell.Value End If Next getmaxvalue = i End Function
Замечания:
- Maximum_range представляет диапазон ячеек, переданных из таблицы Excel в качестве параметра.
- Переменная i объявлена как Double.
- Цикл For повторяется. На каждой итерации условие if проверяет, является ли значение, считанное из соответствующей ячейки, больше, чем i. Если условие оценивается как истина, то значение ячейки присваивается i .
- Когда все ячейки в Maximum_range будут повторены, максимум из них будет назначен i .
- Наконец , я назначен getmaxvalue и возвращен в вызывающую ячейку.
Результат будет таким, как указано ниже.
Вывод
Функция VBA max используется для поиска максимального значения из диапазона чисел. Для выполнения расчетов требуется функциональная процедура. Dim используется для определения переменных. Функция завершения используется для завершения функции. Он выполняет задачу очень быстро и точно. Хотя это не встроенная функция в Excel VBA, однако, используя процедуру функции, мы можем выполнить функцию max в VBA Excel.
Рекомендуемая статья
Это руководство по VBA MAX. Здесь мы обсудим, как использовать функцию MAX в Excel VBA вместе с практическими примерами и загружаемым шаблоном Excel. Вы также можете просмотреть наши другие предлагаемые статьи —
- Создание объекта коллекции в Excel VBA
- VBA IF Заявления | Шаблоны Excel
- Как использовать функцию сортировки Excel VBA?
- VBA While Loop (Примеры с шаблоном Excel)
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