Vba excel наибольшее число

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

VBA Max

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Max (wallstreetmojo.com)

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

VBA MAX Example 1

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.

VBA MAX Example 1-1

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.

Example 2

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.

Example 2-1

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

Example 2-2

It will identify the maximum number easily.

Run the code manually or press the F5 key to see the result below.

VBA MAX Example 2-3

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

Example 2-4

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.

VBA MAX Example 2-5

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

  • Что такое 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. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. Создание объекта коллекции в Excel VBA
  2. VBA IF Заявления | Шаблоны Excel
  3. Как использовать функцию сортировки Excel VBA?
  4. VBA While Loop (Примеры с шаблоном Excel)

Содержание

  1. VBA MAX — Нахождение максимального значения из диапазона чисел в Excel
  2. Что такое Max Function в VBA?
  3. Как включить вкладку «Разработчики»?
  4. Как использовать функцию Max в Excel VBA?
  5. VBA Max — Пример № 1
  6. VBA Max — Пример № 2
  7. VBA Max — Пример № 3
  8. VBA Max — Пример № 4
  9. Вывод
  10. Рекомендуемая статья
  11. Метод WorksheetFunction.Max (Excel)
  12. Синтаксис
  13. Параметры
  14. Возвращаемое значение
  15. Замечания
  16. Поддержка и обратная связь
  17. VBA Max
  18. Excel VBA Max Function
  19. Example of Max Function in Excel VBA
  20. Advanced Example of Max in Excel VBA
  21. Things to Remember
  22. Recommended Articles

VBA MAX — Нахождение максимального значения из диапазона чисел в Excel

Что такое 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.

Код:

Замечания:

  • Упомяните тип данных переменных через dim .
  • Присвойте числа переменным.

Запустите код, нажав клавишу F5 или нажав кнопку воспроизведения. Результат будет отображен в окне сообщения.

VBA Max — Пример № 2

Возьмите четыре числа 15, 34, 50, 62. Узнайте максимальное число, используя функцию Max.

Код:

Замечания:

  • Здесь мы прямо присвоили номера четырем различным переменным, не упоминая их тип данных. Программа автоматически решает тип данных.
  • Использовали эти переменные в формуле и получили результат в окне сообщения.

Запустите код, нажав клавишу F5 или нажав кнопку воспроизведения. Результат будет отображен в окне сообщения.

VBA Max — Пример № 3

Найдите максимальное значение из диапазона, используя функцию Max.

Код:

Замечания:

  • Функциональная процедура в коде 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.

Код:

Замечания:

  • 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. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. Создание объекта коллекции в Excel VBA
  2. VBA IF Заявления | Шаблоны Excel
  3. Как использовать функцию сортировки Excel VBA?
  4. VBA While Loop (Примеры с шаблоном Excel)

Источник

Метод WorksheetFunction.Max (Excel)

Возвращает наибольшее значение в наборе значений.

Синтаксис

Выражение Переменная, представляющая объект WorksheetFunction .

Параметры

Имя Обязательный или необязательный Тип данных Описание
Arg1Arg30 Обязательный Variant Number1, number2. — от 1 до 30 чисел, для которых требуется найти максимальное значение.

Возвращаемое значение

Double

Замечания

Аргументы могут быть числами или именами, массивами или ссылками, содержащими числа.

Учитываются логические значения и текстовые представления чисел, которые вы вводите непосредственно в список аргументов.

Если аргумент является массивом или ссылкой, используются только числа в этом массиве или ссылке. Пустые ячейки, логические значения или текст в массиве или ссылке игнорируются.

Если аргументы не содержат чисел, max возвращает значение 0 (ноль).

Аргументы, которые являются значениями ошибок или текстом, которые не могут быть преобразованы в числа, вызывают ошибки.

Если вы хотите включить логические значения и текстовые представления чисел в ссылку в рамках вычисления, используйте функцию MAXA.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA Max

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 MAX Excel Function Called MAX The 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

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA Max (wallstreetmojo.com)

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:

We have declared three variables to store the number in the above example.

We have declared one more variable to show the results.

For the first 3 three variables, we assigned values like 50, 25, and 60, respectively.

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:

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:

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 excelMIN 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 Max

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.

Open File

Step 2: Click on Options.

Options

Step 3: In a window opening up named Excel Options, click on Customize Ribbon to access the ribbon customization options.

Customize Ribbon

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.

Developer(Custom) option

Step 5: Click on the Developer tab and then click the Visual Basic (ALT +F11) icon.

Developer Tab>Visual Basic

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

Max number Example 1

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.

Message Box Example 1-1

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

VBA Max Example 2

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.

Message Box Example 2-2

VBA Max – Example #3

Find the maximum value from the range by using the Max function.

VBA Max Example 3-1

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

VBA Max Example 4

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).

VBA MAX Function Example 3-2

The result will be as given below.

VBA Max Example 3-3

VBA Max – Example #4

Find the maximum value from the range by using the Max function.

VBA MAX Function Example 4-1

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

Range Example 4

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.

getmaxvalue Example 4-4

The result will be as given below.

getmaxvalue Example 4-5

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 –

  1. VBA Solver
  2. VBA IF Statements
  3. VBA Sort
  4. VBA While Loop

Finding Smallest and Largest Value with VBA. Using ParamArray to find Minimum Value.

Related Links:

Remove Duplicates in a range, using «Find ‘Smallest’, ‘Largest’, ‘K-th Smallest’ and ‘K-th Largest’ Numbers in a Range, with Excel Functions.

————————————————————————————————  

Contents:

Determine smallest value in range

Determine largest value in range

Determine smallest value in each non-blank row and display message mentioning row no. and the value

Determine smallest value in range, highlight and return its address

Determine Minimum Value from a List

Determine Maximum Value from a List

Determine Minimum Value from a Parameter Array

————————————————————————————————


Determine smallest value in range

Sub Smallest()
‘Cells with dates also return a value, and get covered for determining smallest value. Percentages will convert and return numerics.

Dim rng As Range
Dim dblMin As Double

‘Set range from which to determine smallest value
Set rng = Sheet1.Range(«A1:Z100»)

‘Worksheet function MIN returns the smallest value in a range 

dblMin = Application.WorksheetFunction.Min(rng)

‘Displays smallest value
MsgBox dblMin

End Sub


Determine largest value in range

Sub Largest()
‘Cells with dates also return a value, and get covered for determining largest value. Percentages will convert and return numerics.

Dim rng As Range
Dim dblMax As Double

‘Set range from which to determine largest value
Set rng = Sheet1.Range(«A1:Z100»)

‘Worksheet function MAX returns the largest value in a range 

dblMax = Application.WorksheetFunction.Max(rng)

‘Displays largest value
MsgBox dblMax

End Sub


Determine smallest value in each non-blank row and display message mentioning row no. and the value.

Sub rowSmallest()
‘Cells with dates also return a value, and get covered for determining smallest value. Percentages will convert and return numerics.

Dim rng As Range
Dim currentRow As Long
Dim dblMin As Double
Dim lastRow As Long

‘Determines the last used row number in worksheet
lastRow = Sheet1.UsedRange.Row — 1 + Sheet1.UsedRange.Rows.Count

For currentRow = 1 To lastRow
Set rng = Sheet1.Rows(currentRow)

‘Checks for empty rows provided there are no formulas (including =»» ) or spaces present in any of the cells 
If WorksheetFunction.CountA(rng) = 0 Then

MsgBox «Row » & currentRow & » is blank.»

Else

dblMin = Application.WorksheetFunction.Min(rng)
MsgBox «The smallest value in row » & currentRow & » is » & dblMin

End If

Next currentRow

End Sub


Determine smallest value in range, highlight and return its address

Sub Smallest_Value_Highlight_Address()
‘Determines smallest value in range, highlights it and returns its address
‘Cells with dates also return a value, and get covered for determining smallest value. Percentages will convert and return numerics.
‘Determines values from the active worksheet

Dim strData As String
Dim rng As Range
Dim vValue As Variant
Dim rngCol As Range
Dim lngRow As Long

Dim rngAdd As Range

‘Enter desired range in which to find the smallest value

strData = «A1:Z100«

Set rng = Range(strData)

‘Determines smallest value in range
vValue = Application.WorksheetFunction.Min(rng)

For Each rngCol In rng.Columns

‘Determines in case the smallest value exists in a particular column

If Application.WorksheetFunction.CountIf(rngCol, vValue) > 0 Then

‘Returns row number of the smallest value, in the column which has the same

lngRow = Application.WorksheetFunction.Match(vValue, rngCol, 0)

 
‘Returns cell address of the smallest value

Set rngAdd = rngCol.cells(lngRow, 1)

    
‘Selects smallest value to highlight with color

rngAdd.Select

With Selection

.Interior.Color = RGB(255, 255, 0)

End With

        
‘Message displays the searched range, smallest value, and its address

MsgBox «Smallest Value in Range(«»» & strData & «»») is » & vValue & «, in Cell » & rngAdd.Address & «.»

Exit Sub

End If

Next

End Sub
 


————————————————————————————————————————————————————-
‘ParamArray (Parameter Array): It is not possible to call a procedure with more arguments than the procedure declaration specifies. VBA allows use of optional parameters but you have to know the number of elements in the array ahead of time, when you define the procedure. The ParamArray keyword lets you pass in any number of values. The function receives them as an array. The ParamArray argument makes it possible for a procedure (a function or a subroutine) to accept an arbitrary number of arguments, each of a possibly different type (by using a Variant).

————————————————————————————————————————————————————-

Determine Minimum Value from a List

Function MinInList(ParamArray ArrayList() As Variant)
‘Function will return the minimum value from a list of values

   Dim n As Integer
Dim iValue As Variant

‘Set the variable iValue — initialize to the first item or value in list.   
iValue = ArrayList(0)

‘Checks each item or value in the list to find the smallest.
‘The UBound function is used with the LBound function to determine the size of an array. Use the LBound function to find the lower limit of an array dimension. Since array subscripts start at 0, the length of a dimension is greater by one than the highest available subscript for that dimension. The largest available subscript for the indicated dimension of an array can be obtained by using the Ubound function.
For n = 0 To UBound(ArrayList)

‘Determines the smallest value.

If ArrayList(n) < iValue Then
iValue = ArrayList(n)
End If

Next n

MinInList = iValue

   End Function

Sub SmallestValueInList()
‘Returns minimum value from a List — Calls Function MinInList.

‘Cells(16, 5) contains -308, Range(«B13») contains -400 and Range(«D19») contains the date «2/1/2011». Value returned is -400, being the smallest.
MsgBox MinInList(1, -5, 3, -8, -9, hello, 10 * -1, cells(16, 5), Range(«B13»), Range(«D19»))

‘Range(«D19») contains the date «2/1/2011», Range(«H8») contains the date «3/5/2010» and Range(«I10») contains the date «3/5/2009». Date returned is «3/5/2009», being the smallest.
MsgBox MinInList(Range(«D19»), Range(«H8»), Range(«I10»))

End Sub


Determine Maximum Value from a List 

Function MaxInList(ParamArray ArrayList() As Variant)
‘Function will return the maximum value from a list of values

   Dim n As Integer
Dim iValue As Variant

‘Set the variable iValue — initialize to the first item or value in list.   
iValue = ArrayList(0)

‘Checks each item or value in the list to find the largest.
For n = 0 To UBound(ArrayList)

‘Determines the largest value.

If ArrayList(n) > iValue Then
iValue = ArrayList(n)

Next n

MaxInList = iValue

   End Function

Sub LargestValueInList()
‘Returns maximum value from a List- Calls Function MaxInList.

‘Range(«K7») contains 3000. Value returned and displayed in message box is 3000, being the largest.
MsgBox MaxInList(1, -5, 3, -8, -9, hello, 10 * -1, Range(«K7»))

‘Range(«D19») contains the date «2/1/2011», Range(«H8») contains the date «3/5/2010» and Range(«I10») contains the date «3/5/2009». Date returned is «2/1/2011», being the largest.
MsgBox MaxInList(Range(«D19»), Range(«H8»), Range(«I10»))


Determine Minimum Value from a Parameter Array (also works for nested array or a multiple column range)

Function minimum(ParamArray Values() As Variant)
‘Returns minimum value from a Parameter Array (also works for nested array or a multiple column range).

   Dim Item As Variant
Dim Part As Variant

   
For Each Item In Values

‘Checks if an item in the array of Values is itself an array (viz. nested array) and determines minimum value therein
If IsArray(Item) Then

For Each Part In Item

minimum = minimum(Part, minimum)

Next

‘If an item in the array of Values is not an array 

If Not IsEmpty(minimum) Then

If Item < minimum And Not IsEmpty(Item) Then

minimum = Item

End If

Else

minimum = Item

End If

End If

Next

   
End Function

Sub SmallestValue()
‘Returns minimum value from a Parameter Array (also works for nested array or a multiple column range).

‘Returns -25.
MsgBox minimum(Array(11, 20, -16), -14, hello, -18.5, Array(1, Array(1 * -25, -21, -1), -11))

‘Returns 11.
MsgBox minimum(16.5, 11, 20)

‘Returns -7700, smallest value in range which is in cell «B27».
MsgBox minimum(Range(«A1:Z100»))

‘Cells(16, 5) contains -308, Range(«B13») contains -400 and Range(«D19») contains the date «2/1/2011». Value returned is -400, being the smallest.
MsgBox minimum(1, -5, 3, -8, -9, hello, 10 * -1, cells(16, 5), Range(«B13»), Range(«D19»))

‘Range(«D19») contains the date «2/1/2011», Range(«H8») contains the date «3/5/2010» and Range(«I10») contains the date «3/5/2009». Date returned is «3/5/2009», being the smallest.
MsgBox minimum(Range(«D19»), Range(«H8»), Range(«I10»))

Понравилась статья? Поделить с друзьями:
  • Vba excel назначить кнопка макрос
  • Vba excel название месяца по номеру
  • Vba excel название книги
  • Vba excel нажать кнопку
  • Vba excel нажатие enter