Vba как найти максимальное значение столбца

You can indeed use the function application.worksheetfunction.max(rng) as noted. To give a bit more complete answer, almost ANY Excel formula that’s available on the worksheet is available to use in the VBA code window via the application.worksheetfunction collection. This includes max, min, sumif, vlookup, etc.

This should give you the same on-screen description of the arguments involved in the function that you do when using the function on a worksheet. However, as another use noted, using application.max(range) does not give the same argument help. Also as same user noted, there’s a difference in error handling between using application.max(rng) and worksheetfunction.max(rng), you can see this in the comment below

As for a programming logic to determine a max value from a list of values, the basic logic is this:

max = 0 'set "inital" max 
For Each rcell in rrng.cells 'loop through values
   if rcell.value > max then 'if a value is larger than the old max, 
   max = rcell.value ' store it as the new max!
Next rcell 

This will often work, but is missing a reference:

 worksheets("Data").Cells(Count, 4)=  Application.WorksheetFunction.Max _
    ( worksheets("Data").range( cells(m,1) ,cells(n,1) )

The text «cells» should be preceded by a reference to which worksheet the cells are on, I would write this:

worksheets("Data").Cells(Count, 4) = Application.WorksheetFunction.Max _
    ( worksheets("Data").range( worksheets("Data").cells(m,1) ,worksheets("Data").cells(n,1) )

This can also be written like this which is clearer:

with worksheets("Data")
    .Cells(Count, 4) =  Application.WorksheetFunction.Max _
                            ( .range( .cells(m,1) ,.cells(n,1) )
End With 

I hope this helps.

Harvey

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 / 1 / 0

Регистрация: 04.05.2011

Сообщений: 32

1

Excel

Максимальное значение

13.05.2019, 13:38. Показов 29095. Ответов 16


Студворк — интернет-сервис помощи студентам

Добрый день, даны два столбца дробных значений (А1:А47 и В1:В47), нужно, с помощью макроса, из столбца В найти максимальное значение, а затем найти в А соответствующее значение для В максимального и вывести эти числа на экран.



0



Kate_27

198 / 132 / 67

Регистрация: 27.03.2019

Сообщений: 288

13.05.2019, 13:52

2

Добрый день,
можно вот так:

Visual Basic
1
2
3
4
5
6
7
8
9
10
Sub MaximumAB()
    Dim B As Double
    Dim i As Integer
    Dim Msg As String
    B = Application.Max(Range("B1:B47"))
    For i = 1 To 47
        If Cells(i, 2) = B Then Msg = Msg & Cells(i, 1).Value & vbTab
    Next i
    MsgBox "Значения в А, соответствующие максимальному значению в В: " & Msg
End Sub



1



1 / 1 / 0

Регистрация: 04.05.2011

Сообщений: 32

13.05.2019, 14:06

 [ТС]

3

Только мне надо, чтобы значения были выведены в ячейку, например, в Д 2 и С 2



0



1 / 1 / 0

Регистрация: 04.05.2011

Сообщений: 32

13.05.2019, 14:12

 [ТС]

4

Kate_27, приложила файл



0



Kate_27

198 / 132 / 67

Регистрация: 27.03.2019

Сообщений: 288

13.05.2019, 14:18

5

лялячка,
Тогда так:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
Sub MaximumAB()
    Dim B As Double
    Dim i As Integer
    Dim Msg As String
    Dim k As Integer
    B = Application.Max(Range("B1:B47"))
    For i = 1 To 47
        If Cells(i, 2) = B Then
            Cells(2, 3 + k) = Cells(i, 1)
            k = k + 1
        End If
    Next i
End Sub

Добавлено через 3 минуты
лялячка,
Мне не понятно в файле куда выводить значения.
Либо скажите в какие ячейки, либо сами подкорректируйте строку кода:
Cells(2, 3 + k) = Cells(i, 1) на то, что Вам нужно



1



1 / 1 / 0

Регистрация: 04.05.2011

Сообщений: 32

13.05.2019, 14:37

 [ТС]

6

В ячейку Н2 поместить максимальное число из столбца в, а в G2 соотвествующее маскимальному числу в , число из столбца а. Вот как -то так . Спасибо!!!!!!!!!!!!!!



0



Kate_27

198 / 132 / 67

Регистрация: 27.03.2019

Сообщений: 288

13.05.2019, 14:44

7

лялячка, Я так понимаю 2 максимальных значений в Вашем случае быть не может? Тогда можно цикл переписать так:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
Sub MaximumAB() 
    Dim b As Double
    Dim i As Integer
    b = Application.Max(Range("B1:B47"))
    For i = 1 To 47
        If Cells(i, 2) = b Then
            Range("H2") = b
            Range("G2") = Cells(i, 1)
            Exit For
        End If
    Next i
End Sub



0



1 / 1 / 0

Регистрация: 04.05.2011

Сообщений: 32

13.05.2019, 18:39

 [ТС]

8

Спасибо, сделала, как вы написали, но поняла, что максимумов несколько, и мне надо взять последнее, в условии прописала (6 строчка) >=b , выводит в ячейку н2 верное значение, однако в g2 выводит неверное число, пишет там сигма. И еще мне надо столбик в разделить на ячейку h2 и вывести эти числа в столбик д, и столбик а разделить на g2 и вывести результат в столбец с, тоже с помощью макроса, вроде начала делать, но походу не правильно. Посмотрите, пожалуйста.



0



198 / 132 / 67

Регистрация: 27.03.2019

Сообщений: 288

13.05.2019, 20:24

9

лялячка, давайте так.
Киньте файл и сформируйте задачу правильно. Откуда брать данные, какой ожидается результат и куда этот результат вывести.
Просто создаётся ощущение, что вы сами не знаете чего хотите получить.



0



лялячка

1 / 1 / 0

Регистрация: 04.05.2011

Сообщений: 32

14.05.2019, 09:11

 [ТС]

10

Добрый день, файл с макросом не прикладывается, прикладываю без макроса, есть два столбика: 1. Из столбца В, выбрать самый последний максимум (число, которое располагается в 31 строке) и вывести в ячейку Н2. 2. Из столбца А, взять число которое стоит напротив В максимального (число, которое тоже располагается в 31 строке но в столбце А) и поместить его в G2.

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
Sub MaximumAB()
    Dim b As Double
    Dim i As Integer
    b = Application.Max(Range("B1:B47"))
    For i = 1 To 47
        If Cells(i, 2) >= b Then
        Range("H2") = b
        Range("G2") = Cells(i, 1)
    Exit For
        End If
    Next i
End Sub

Вот что я прописала в макросе, он правильно выводит значение В, но в ячейке G2 он вывод слово эксп, а должно быть значение 0,22

Вложения

Тип файла: xlsx 13.05.19.xlsx (11.5 Кб, 4 просмотров)



0



Vlad999

3835 / 2261 / 753

Регистрация: 02.11.2012

Сообщений: 5,959

14.05.2019, 09:32

11

Visual Basic
1
2
3
4
5
6
7
8
9
10
Sub MaximumAB()
Dim b As Double
Dim i As Integer
b = Application.Max(Range("B1:B47"))
For i = 1 To 47
    If Cells(i, 2) = b Then n = Cells(i, 1)
Next i
Range("H2") = b
Range("G2") = n
End Sub

Добавлено через 3 минуты

Цитата
Сообщение от лялячка
Посмотреть сообщение

но в ячейке G2 он вывод слово эксп

это по тому что текст всегда больше числа и условие Cells(i, 2) >= b выполняется в первой же строке.
σэксп > 999,4038217



0



198 / 132 / 67

Регистрация: 27.03.2019

Сообщений: 288

14.05.2019, 09:48

12

лялячка, а зачем Вы условие Cells(i, 2)= b заменили на Cells(i, 2) >= b. Отсюда у Вас ошибка и вышла.

Добавлено через 3 минуты
лялячка, чтобы выбрать самый последний максимум уберите exit For из цикла в моем коде или воспользуйтесь модификацией Vlad999, это по сути тоже самое.



0



1 / 1 / 0

Регистрация: 04.05.2011

Сообщений: 32

14.05.2019, 10:08

 [ТС]

13

Спасибо! Но теперь в G2 он мне 0 выдает(((((а надо 0,22



0



3835 / 2261 / 753

Регистрация: 02.11.2012

Сообщений: 5,959

14.05.2019, 10:19

14

любое утверждение желательно подкреплять файлом.
xlsm в архив тогда прицепится на форум.



0



1 / 1 / 0

Регистрация: 04.05.2011

Сообщений: 32

14.05.2019, 10:35

 [ТС]

15

Приложила



0



3835 / 2261 / 753

Регистрация: 02.11.2012

Сообщений: 5,959

14.05.2019, 10:41

16

почитайте про тип переменных. Integer — это только целые числа, по этому 0,22 округлялось до 0.
Dim n As Double нужно.



0



1 / 1 / 0

Регистрация: 04.05.2011

Сообщений: 32

14.05.2019, 10:52

 [ТС]

17

Огромное спасибо! Все получилось!!!!)))))))



0



VBA — определение максимального значения в колонке

tumanovalex

Дата: Понедельник, 19.01.2015, 21:11 |
Сообщение № 1

Группа: Пользователи

Ранг: Прохожий

Сообщений: 4


Репутация:

0

±

Замечаний:
0% ±


Excel 2007

Есть ли в VBA возможность без цикла определить максимальное значение в числовой колонке? Что либо подобное функции определения числа строк в колонке: Application.WorksheetFunction.CountA(Range(«A:A»))

Сообщение отредактировал tumanovalexПонедельник, 19.01.2015, 21:12

 

Ответить

Gustav

Дата: Понедельник, 19.01.2015, 21:16 |
Сообщение № 2

Группа: Друзья

Ранг: Старожил

Сообщений: 2432


Репутация:

991

±

Замечаний:
0% ±


начинал с Excel 4.0, видел 2.1

Application.WorksheetFunction.Max


МОИ: Ник, Tip box: 41001663842605

 

Ответить

krosav4ig

Дата: Понедельник, 19.01.2015, 23:34 |
Сообщение № 3

Группа: Друзья

Ранг: Старожил

Сообщений: 2346


Репутация:

989

±

Замечаний:
0% ±


Excel 2007,2010,2013

[vba][/vba] :o


email:krosav4ig26@gmail.com WMR R207627035142 WMZ Z821145374535 ЯД 410012026478460

 

Ответить

Gustav

Дата: Вторник, 20.01.2015, 15:33 |
Сообщение № 4

Группа: Друзья

Ранг: Старожил

Сообщений: 2432


Репутация:

991

±

Замечаний:
0% ±


начинал с Excel 4.0, видел 2.1


Точно! Или так:
[vba]

Код

Application.Evaluate(«MAX(A:A,15,30,45.4,B:B)»)

[/vba]


МОИ: Ник, Tip box: 41001663842605

 

Ответить

tumanovalex

Дата: Вторник, 20.01.2015, 15:52 |
Сообщение № 5

Группа: Пользователи

Ранг: Прохожий

Сообщений: 4


Репутация:

0

±

Замечаний:
0% ±


Excel 2007

Спасибо большое всем ответившим!

 

Ответить

Понравилась статья? Поделить с друзьями:
  • Утеряна банковская карта как найти
  • Как пишется ненашел или не нашел
  • Как найти потерянные вещи по маятнику
  • Как найти триггер в powerpoint
  • Как найти телефон знаменитостей