Excel vba worksheetfunction max

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

WorksheetFunction.Max method (Excel)

vbaxl10.chm137080

vbaxl10.chm137080

excel

Excel.WorksheetFunction.Max

f0b2df1d-3b0e-2387-fa91-f8bf8cb6c4da

05/24/2019

medium

WorksheetFunction.Max method (Excel)

Returns the largest value in a set of values.

Syntax

expression.Max (Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9, Arg10, Arg11, Arg12, Arg13, Arg14, Arg15, Arg16, Arg17, Arg18, Arg19, Arg20, Arg21, Arg22, Arg23, Arg24, Arg25, Arg26, Arg27, Arg28, Arg29, Arg30)

expression A variable that represents a WorksheetFunction object.

Parameters

Name Required/Optional Data type Description
Arg1Arg30 Required Variant Number1, number2… — 1 to 30 numbers for which you want to find the maximum value.

Return value

Double

Remarks

Arguments can either be numbers or names, arrays, or references that contain numbers.

Logical values and text representations of numbers that you type directly into the list of arguments are counted.

If an argument is an array or reference, only numbers in that array or reference are used. Empty cells, logical values, or text in the array or reference are ignored.

If the arguments contain no numbers, Max returns 0 (zero).

Arguments that are error values or text that cannot be translated into numbers cause errors.

If you want to include logical values and text representations of numbers in a reference as part of the calculation, use the MAXA function.

[!includeSupport and feedback]

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

Содержание

  1. Метод WorksheetFunction.Max (Excel)
  2. Синтаксис
  3. Параметры
  4. Возвращаемое значение
  5. Замечания
  6. Поддержка и обратная связь
  7. WorksheetFunction.Max method (Excel)
  8. Syntax
  9. Parameters
  10. Return value
  11. Remarks
  12. Support and feedback
  13. Name already in use
  14. VBA-Docs / api / Excel.WorksheetFunction.Max.md
  15. VBA MAX — Нахождение максимального значения из диапазона чисел в Excel
  16. Что такое Max Function в VBA?
  17. Как включить вкладку «Разработчики»?
  18. Как использовать функцию Max в Excel VBA?
  19. VBA Max — Пример № 1
  20. VBA Max — Пример № 2
  21. VBA Max — Пример № 3
  22. VBA Max — Пример № 4
  23. Вывод
  24. Рекомендуемая статья
  25. MAX Function Examples In Excel, VBA, & Google Sheets
  26. MAX Function Overview
  27. MAX function Syntax and inputs:
  28. How To Use The MAX Function
  29. Empty Cells or Cells With Text
  30. MAX Date
  31. VLOOKUP & MAX
  32. MAXIFS Function
  33. MAX IF
  34. MAX function in Google Sheets
  35. Additional Notes
  36. MAX Examples in VBA

Метод WorksheetFunction.Max (Excel)

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

Синтаксис

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

Параметры

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

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

Double

Замечания

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

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

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

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

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

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

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

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

Источник

WorksheetFunction.Max method (Excel)

Returns the largest value in a set of values.

Syntax

expression A variable that represents a WorksheetFunction object.

Parameters

Name Required/Optional Data type Description
Arg1 – Arg30 Required Variant Number1, number2. — 1 to 30 numbers for which you want to find the maximum value.

Return value

Double

Arguments can either be numbers or names, arrays, or references that contain numbers.

Logical values and text representations of numbers that you type directly into the list of arguments are counted.

If an argument is an array or reference, only numbers in that array or reference are used. Empty cells, logical values, or text in the array or reference are ignored.

If the arguments contain no numbers, Max returns 0 (zero).

Arguments that are error values or text that cannot be translated into numbers cause errors.

If you want to include logical values and text representations of numbers in a reference as part of the calculation, use the MAXA function.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Name already in use

VBA-Docs / api / Excel.WorksheetFunction.Max.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

WorksheetFunction.Max method (Excel)

Returns the largest value in a set of values.

expression A variable that represents a WorksheetFunction object.

Name Required/Optional Data type Description
Arg1Arg30 Required Variant Number1, number2. — 1 to 30 numbers for which you want to find the maximum value.

Double

Arguments can either be numbers or names, arrays, or references that contain numbers.

Logical values and text representations of numbers that you type directly into the list of arguments are counted.

If an argument is an array or reference, only numbers in that array or reference are used. Empty cells, logical values, or text in the array or reference are ignored.

If the arguments contain no numbers, Max returns 0 (zero).

Arguments that are error values or text that cannot be translated into numbers cause errors.

If you want to include logical values and text representations of numbers in a reference as part of the calculation, use the MAXA function.

Источник

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)

Источник

MAX Function Examples In Excel, VBA, & Google Sheets

Download the example workbook

This tutorial demonstrates how to use the Excel MAX Function in Excel to calculate the largest number.

MAX Function Overview

The MAX Function Calculates the largest number.

To use the MAX Excel Worksheet Function, select a cell and type:

(Notice how the formula inputs appear)

MAX function Syntax and inputs:

array – An array of numbers.

How To Use The MAX Function

The MAX Function returns the largest value from a set of data.

Here let’s use the MAX Function to find the highest GDP in the world:

Empty Cells or Cells With Text

The MAX Function ignores cells that are empty or that contain non-numeric values.

MAX Date

Since Excel stores date as serial numbers, we can use the MAX Function to find the maximum date.

VLOOKUP & MAX

In our above example, we used the MAX Function to determine the highest GDP in the world. After finding the MAX GDP, we can use the VLOOKUP Function to find the country with the highest GDP:

The above function calculates the highest GDP by using the MAX Function. The VLOOKUP Function searches for the highest GDP and returns the information from the second column (as indicated by “2” in our formula) of the search range (A2:B9).

Note: The item we are looking for (GDP) must be in the first column when using the VLOOKUP Function.

MAXIFS Function

MAXIFS Function returns the maximum value from a data range based on one or more criteria. From our GDP example, suppose we want to find the highest GDP of an Asian country. Use the formula:

The function narrows down its data range by applying the conditions we provided. It looks for Asia in B2:B11, thus creating a subset from the original data range. The maximum value is then calculated from this subset of data.

To learn more about how the MAXIFS Function works, read our tutorial on MAXIFS and MINIFS.

Note: MAXIFS Function is only available in Excel 2019 or Excel 365. If you have an older Excel version, you can use Array Function to make your own MAX IF.

MAX IF

If you are using older Excel versions, you can combine IF Function with MAX Function using an Array Function. Taking the same example as above, use the formula:

Note: When building array functions, you must press CTRL + SHIFT + ENTER instead of just ENTER after creating your formula.

You’ll notice how the curly brackets appear. You can not just manually type in the curly brackets; you must use CTRL + SHIFT + ENTER.

The formula creates a subset of GDP by using the search criteria. The IF Function searches for “Asia” in B2:B11 and returns the corresponding values from C2:C11 to the MAX Function. Thus, calculating the highest GDP in Asia only.

Note: The above formula uses absolute references (the $ signs) to lock cell references when copying formulas. If you aren’t familiar with this, please read our Excel References Guide

MAX function in Google Sheets

The MAX function works exactly the same in Google Sheets as in Excel.

Additional Notes

The MIN Function returns the smallest number in a series.

MAX Examples in VBA

You can also access the Excel MAX Function from within VBA, using Application.WorksheetFunction.

The statement above will return 30.43 as the max value (21 + 9.43 = 30.43)

MAX can also accept a range (or Named Range) as a parameter as shown in the VBA code below

In addition, MAX can accept the name of a table like the one shown above, as a parameter:

MAX ignores non-numeric values, so the result of the code above is 80.

Источник

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

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)

Понравилась статья? Поделить с друзьями:
  • Excel vba thisworkbook range
  • Excel vba this worksheets
  • Excel vba worksheet worksheets
  • Excel vba this worksheet range
  • Excel vba worksheet protect