Vba excel минимальное значение в диапазоне

The Excel MIN function returns the smallest value from a specified range of numeric values

Example: Excel MIN Function

Excel MIN Function

METHOD 1. Excel MIN Function

EXCEL

Result in cell C10 (-7) — returns the smallest numeric value from the selected range.

Result in cell D10 (2) — returns the smallest numeric value from the selected range.

METHOD 2. Excel MIN function using the Excel built-in function library

EXCEL

Formulas tab > Function Library group > More Functions > Statistical > MIN > populate the input box

=MIN(C5:C9)
Note: in this example we are populating an input box with a single range.
Built-in Excel MIN Function

METHOD 1. Excel MIN function using VBA

VBA

Sub Excel_MIN_Function()

‘declare a variable
Dim ws As Worksheet

Set ws = Worksheets(«MIN»)

‘apply the Excel MIN function
ws.Range(«C10») = Application.WorksheetFunction.Min(ws.Range(«C5:C9»))
ws.Range(«D10») = Application.WorksheetFunction.Min(ws.Range(«D5:D9»))

End Sub

OBJECTS
Worksheets: The Worksheets object represents all of the worksheets in a workbook, excluding chart sheets.
Range: The Range object is a representation of a single cell or a range of cells in a worksheet.

PREREQUISITES
Worksheet Name: Have a worksheet named MIN.

ADJUSTABLE PARAMETERS
Output Range: Select the output range by changing the Range references («C10») and («D10») in the VBA code to any cell in the worksheet, that doesn’t conflict with the formula.

Usage of the Excel MIN function and formula syntax

EXPLANATION

DESCRIPTION
The Excel MIN function returns the smallest value from a specified range of numeric values.

SYNTAX
=MIN(number1, [number2], …)

ARGUMENT(S)
number1: (Required) A single numeric cell or a range of numeric cells.
number2: (Optional) A single numeric cell or a range of numeric cells.

ADDITIONAL NOTES
Note 1: In Excel 2007 and later the MIN function can accept up to 255 number arguments. In Excel 2003 the MIN function can only accept up to 30 number arguments.

 

Leo

Пользователь

Сообщений: 115
Регистрация: 01.01.1970

Добрый вечер! Я начал изучать VBA, и столкнулся с рядом проблем. Поэтому обращаюсь к вам с просьбой помочь мне разобраться.  
Я хочу получить функцию Минимум из диапазона ячеек, которые можно указать с помощью открывающегося окна 1)с помощью циклов, и 2)с помощью функции min.  
Также не  могу понять что нужно писать в inputBox.  

  Заранее багодарю за помощь:)

 

Kuzmich

Пользователь

Сообщений: 7998
Регистрация: 21.12.2012

Примените метод InputBox    
объекта Application с параметром Type:=8

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Я использую функцию рабочего листа:  
MsgBox Application.WorksheetFunction.Min(Range(«A1:A10»))  
А что нужно писать в InputBox — Вам решать. Посмотрите справку

 

{quote}{login=Юрий М}{date=27.03.2011 10:59}{thema=}{post}Я использую функцию рабочего листа:  
MsgBox Application.WorksheetFunction.Min(Range(«A1:A10»))  
А что нужно писать в InputBox — Вам решать. Посмотрите справку{/post}{/quote}  
да, так работает, но я хочу что-то типа вот так:  
function min()  
Dim x As Variantx = InputBox(«Ââåäèòå äèàïàçîí ÿ÷ååê», «Ââîä äèàïàçîíà», «D2:D25»)  
ActiveCell = Application.WorksheetFunction.min(Range(x))  
End Funktion  

  Только хочу еще с циклом вариант и как то странно оно работает — в рабочей книге нормально, а применительно к другим відает ошибку…

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Копируйте код при раскладке клавиатуры RU

 

Leo

Пользователь

Сообщений: 115
Регистрация: 01.01.1970

Function min1()  
Dim x As Variant  
x = InputBox(«Ââåäèòå äèàïàçîí ÿ÷ååê», «Ââîä äèàïàçîíà», «D2:D25»)  
ActiveCell = Application.WorksheetFunction.min(Range(x))  
End Function

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Переменную х следует объявить as Range

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Если с первого раза непонятно: Копируйте код при раскладке клавиатуры RU

 

Leo

Пользователь

Сообщений: 115
Регистрация: 01.01.1970

Function min1()  
Dim x As Variant  
x = InputBox(«Введите диапазон ячеек», «Ввод диапазона», «D2:D25»)  
ActiveCell = Application.WorksheetFunction.min(Range(x))  
End Function

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Sub www()  
Dim x As Range  
Set x = Application.InputBox(Prompt:=»Выделяем мыхой диапазон ячеек», Title:=»Выбираем диапазон», Type:=8)  
MsgBox Application.WorksheetFunction.Min(x)  
End Sub

 

Leo

Пользователь

Сообщений: 115
Регистрация: 01.01.1970

{quote}{login=Юрий М}{date=28.03.2011 12:15}{thema=}{post}Sub www()  
Dim x As Range  
Set x = Application.InputBox(Prompt:=»Выделяем мыхой диапазон ячеек», Title:=»Выбираем диапазон», Type:=8)  
MsgBox Application.WorksheetFunction.Min(x)  
End Sub{/post}{/quote}  

  А зачем добавлять слова Promt и title?

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Чтобы было :-) Можете удалить, оставив только текст в кавычках. Проблема только с этим?

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

Люди!  
Если у вас в таблицах есть условное форматирование с формулами, не юзайте Application.InputBox(… Type:=8) !  
Глючит, зараза, если пытаешься указать диапазон на другом листе или в другой книге! На том же листе, вроде работает.  
Код с ним, конечно, упрощается. Но макросы получаются не всегда и не во всех книгах/листах работающими.

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

{quote}{login=Alex_ST}{date=28.03.2011 08:24}{thema=}{post}Люди!  
Если у вас в таблицах есть условное форматирование с формулами, не юзайте Application.InputBox(… Type:=8) !  
Глючит, зараза, если пытаешься указать диапазон на другом листе или в другой книге! На том же листе, вроде работает.  
Код с ним, конечно, упрощается. Но макросы получаются не всегда и не во всех книгах/листах работающими.{/post}{/quote}  
.

 

Property Get в обычном модуле (не в модуле класса)?!  
В чем отличие от Function — просветите, пожалуйста.  
Заменил на Function — работает так же (2007).

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

Неизвестный мастер!  
Я же предупреждал об Application.InputBox(… Type:=8), а в вашем примере это не используется. А предложена его полноценная замена.  
Ваше решение очень интересное тем, что не требует юзерформы с рефэдитом, которой мне пришлось заменить Application.InputBox(… Type:=8) во всех своих макросах, где требовался ввод диапазона мышкой с листа.  
Ща обследую хорошенько ваш метод «во всех позах» и если пройдёт, начну перелопачивать свои макросы.  
Спасибо.

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

{quote}{login=Казанский}{date=28.03.2011 02:45}{thema=}{post}Property Get в обычном модуле (не в модуле класса)?!  
В чем отличие от Function — просветите, пожалуйста.  
Заменил на Function — работает так же (2007).{/post}{/quote}  
Property Get — это именно функция, в том смысле, что returns только значение.  
Function — шизофренична:  
1. Может работать как Sub — не возвращая ничего.  
2. [Public] в стандартном не Option Private Module’е — становится функцией рабочего листа,
а в данном случае оно Вам надо ? Попробуйте (по ошибке) ввести её в ячейку.

 

Поправка:  
… в том смысле, что returns ВСЕГДА (но не только) значение.

 

> 1. Может работать как Sub — не возвращая ничего  
По-моему, это удобно. Например, функция сообщает результат работы как true/false — успешно/неуспешно. Хотим — анализируем, хотим — нет.  

  > 2. [Public] в стандартном не Option Private Module’е — становится функцией рабочего листа, а в данном случае оно Вам надо ? Попробуйте (по ошибке) ввести её в ячейку.

  Попробовал. Оказывается, Application.InputBox и простой InputBox можно вызывать из функции рабочего листа! Интересная фича — если поставить application.volatile, то будет запрашивать юзера при каждом пересчете. Что-то вроде поля ASK в Word.

 

1. А я не говорил, что это неудобно, а только двойственности (даже тройственности) её поведения.  
2.»Попробовал…» — здесь я не уловил Вашу интонацию: обрадавались или огорчились ?  
{quote}{login=Казанский}{date=28.03.2011 02:45}{thema=}{post}  
Заменил на Function — работает так же (2007).{/post}{/quote}  
(разговор о замене ‘Property Get RangeInputBox’ на ‘Function RangeInputBox’)

 

Leo

Пользователь

Сообщений: 115
Регистрация: 01.01.1970

{quote}{login=}{date=28.03.2011 01:11}{thema=}{post}{quote}{login=Alex_ST}{date=28.03.2011 08:24}{thema=}{post}Люди!  
Если у вас в таблицах есть условное форматирование с формулами, не юзайте Application.InputBox(… Type:=8) !  
Глючит, зараза, если пытаешься указать диапазон на другом листе или в другой книге! На том же листе, вроде работает.  
Код с ним, конечно, упрощается. Но макросы получаются не всегда и не во всех книгах/листах работающими.{/post}{/quote}  
.{/post}{/quote}  
Не работает:(    
Метод Юрия работает:)У меня еще вопрос, можно ли записать макрос через цикл?

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

«Макрос через цикл» всегда можно :-) Если объясните — что это такое.

 

Hugo

Пользователь

Сообщений: 23251
Регистрация: 22.12.2012

Это вероятно так — сперва задаём переменной заведомо большое значение, затем в цикле сравниваем с значением текущей ячейки и меняем на текущее, если оно меньше.

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

:-) Не — загоняем всё в массив, циклом перебираем (не знаю зачем). Делаем сортировку, выгружаем во второй массив, из него на лист — что сверху — минимальное.

 

{quote}{login=Юрий М}{date=28.03.2011 10:33}{thema=}{post}:-) Не — загоняем всё в массив, циклом перебираем (не знаю зачем). Делаем сортировку, выгружаем во второй массив, из него на лист — что сверху — минимальное.{/post}{/quote}  
Спасибо:) Вопрос снимаю — на самом деле просто пытаюсь разобраться в языке, т.к. профессия обязывает. А идея «сортировка и верхнее значение скопировать» мне понравилась:)))

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

Набрался наглости и подсократил и переделал для себя в функцию(чтобы было понятнее и проще встраивать в код) творение неизвестного мастера (а не Z ли это маскируется?).  
Теперь надо в своих макросах юзерформ с рефэдитом, вызываемые вместо глючного Application.InputBox(… Type:=8), на этот код менять.  
Function RangeInputBox(Optional Prompt$ = «Выделите на листе диапазон», Optional Title$ = «Ввод диапазона») As Range  
  Dim sFormula$: sFormula = Application.InputBox(Prompt:=Prompt, Title:=Title, Default:=»=» & Selection.Address, Type:=0)  
  On Error Resume Next  
  Set RangeInputBox = Range(Trim(Mid(Application.ConvertFormula(sFormula, xlR1C1, xlA1, True), 2)))  
  On Error GoTo 0  
End Function

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

Алексей, несколькими постами выше я пытался убедить Вашего тёзку (Казанского), что не надо  
переделывать Свойство_Get в Function.  
Get без своего близнеца Let (Set) — это обычная поцедура-функция.  
А Function автоматом появляется в списке UDF мастера функций — зачем она там ?  
Function RangeInputBox(), внутри себя содержащая Application.InputBox или VBA.InputBox, ВЫЗЫВАЕМАЯ из МАКРОСА, работает как добропорядочная процедура.  
Но как ФУНКЦИЯ РАБОЧЕГО ЛИСТА — это монстр, «чужой», ужас голливудский.

 

{quote}{login=Alex_ST}{date=29.03.2011 10:02}{thema=}{post}… а не Z ли это маскируется?)…{/post}{/quote}  
Вот это комплименты!..  Alex_ST! Неужели нюх подводит?! Кто у нас иногда  ИнкогНиТо на таком уровне способен «хулиганить»?.. Не подсказываю…  
ps А сам я выше рекордера не поднимаюсь ;( , к сожалению… Простите за off…

 

МногимиУважаемыеПланетяне, вы считаете приличным говорить между собой о  
незнакомом вам человеке в его присутствии ?

 

Казанский

Пользователь

Сообщений: 8839
Регистрация: 11.01.2013

#30

29.03.2011 14:22:56

{quote}{login=Неизвестный афтор}{date=29.03.2011 01:24}{thema=}{post}МногимиУважаемыеПланетяне, вы считаете приличным говорить между собой о  
незнакомом вам человеке в его присутствии ?{/post}{/quote}{quote}{login=Неизвестный афтор}{date=29.03.2011 01:24}{thema=}{post}МногимиУважаемыеПланетяне, вы считаете приличным говорить между собой о  
незнакомом вам человеке в его присутствии ?{/post}{/quote}  
А Вы перестаньте быть неизвестным :)  
Когда я увидел Ваше сообщение от 28.03.2011 13:11, то сначала подумал, что это Алексей выложил файл в подтверждение того, что Application.InputBox(… Type:=8) глючит при использовании УФ, и довольно долго пытался получить ошибку. Если бы Вы представились, сразу бы стало понятно, что назначение файла другое.  

  Анонимность уместна для форумов, чье содержание подобно надписям на стенах туалета, типа demotivation. А здесь лучше иметь ник, ИМХО.

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

For a list like:

Column1     Column2     Column3    
DataA       1           1234    
DataA       2           4678    
DataA       3           8910    
DataB       2           1112    
DataB       4           1314    
DataB       9           1516

How do I get a list like this:

Column4    Column5      Column6    
DataA      1            1234    
DataB      2            1112

The key is to only return the minimum value in column2 and its corresponding column3 value.

Ben McCormack's user avatar

Ben McCormack

31.8k46 gold badges145 silver badges221 bronze badges

asked Dec 9, 2009 at 20:08

John M's user avatar

4

Sorry I misunderstood your Question First. Here is a working code that ended up more complex than I wanted it to be :D

Option Explicit

Private Function inCollection(ByRef myCollection As Collection, ByRef value As Variant) As Boolean
    Dim i As Integer
    inCollection = False

    For i = 1 To myCollection.Count
        If (myCollection(i) = value) Then
            inCollection = True
            Exit Function
        End If
    Next i
End Function

Sub listMinimums()

    Dim source As Range
    Dim target As Range
    Dim row As Range
    Dim i As Integer
    Dim datas As New Collection
    Dim minRows As New Collection

    Set source = Range("A2:C5")
    Set target = Range("D2")
    target.value = source.value

    For Each row In source.Rows
        With row.Cells(1, 1)
            If (inCollection(datas, .value) = False) Then
                datas.Add .value
                minRows.Add row.row, .value
            End If
            If (Me.Cells(minRows(.value), 2) > row.Cells(1, 2)) Then
                minRows.Remove (.value)
                minRows.Add row.row, .value
            End If
        End With
    Next row

    'output'
    For i = 1 To minRows.Count
        target(i, 1) = Me.Cells(minRows(i), 1)
        target(i, 2) = Me.Cells(minRows(i), 2)
        target(i, 3) = Me.Cells(minRows(i), 3)
    Next i

    Set datas = Nothing
    Set minRows = Nothing
End Sub

Note: You might want to replace Me with the name of your sheet.

answered Dec 9, 2009 at 21:01

marg's user avatar

margmarg

2,7871 gold badge32 silver badges33 bronze badges

An example using ADO.

Dim cn As Object
Dim rs As Object
Dim strFile As String
Dim strCon As String
Dim strSQL As String
Dim i As Integer

''http://support.microsoft.com/kb/246335

strFile = ActiveWorkbook.FullName
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
    & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")

cn.Open strCon

strSQL = "SELECT Column1, Min(Column3) As MinCol3 FROM [Sheet8$] GROUP BY Column1"

rs.Open strSQL, cn, 3, 3

For i = 0 To rs.fields.Count - 1
    Sheets("Sheet7").Cells(1, i + 1) = rs.fields(i).Name
Next

Worksheets("Sheet7").Cells(2, 1).CopyFromRecordset rs

answered Dec 10, 2009 at 19:39

Fionnuala's user avatar

FionnualaFionnuala

90.1k7 gold badges110 silver badges148 bronze badges

2

Try this:

Public Sub MinList()
    Const clColKey_c As Long = 1&
    Const clColVal_c As Long = 3&
    Dim ws As Excel.Worksheet, objDict As Object
    Dim lRow As Long, dVal As Double, sKey As String
    Dim lRowFrst As Long, lRowLast As Long, lColOut As Long
    Set ws = Excel.ActiveSheet
    Set objDict = CreateObject("Scripting.Dictionary")
    lRowFrst = ws.UsedRange.Row
    lRowLast = ws.UsedRange.Rows.Count
    lColOut = ws.UsedRange.Columns.Count + 1&
    For lRow = lRowFrst To lRowLast
        dVal = Val(ws.Cells(lRow, clColVal_c).Value)
        sKey = ws.Cells(lRow, clColKey_c).Value
        If objDict.Exists(sKey) Then
            If dVal > objDict.Item(sKey) Then objDict.Item(sKey) = dVal
        Else
            objDict.Add sKey, dVal
        End If
    Next
    For lRow = lRowFrst To lRowLast
        ws.Cells(lRow, lColOut).Value = objDict.Item(ws.Cells(lRow, clColKey_c).Value)
    Next
    ws.Cells(1&, lColOut).Value = "Min"
End Sub

answered Dec 11, 2009 at 13:35

Oorang's user avatar

OorangOorang

6,6001 gold badge34 silver badges52 bronze badges

all_angarsk, Вы меня не поняли. Я имел ввиду, что не нужно усложнять. Любой модуль/процедуру Вы легко отправите в экспорт на флэшку в формате *.bas. И так точно вытянете его оттуда в любом месте, на любом компе, в любой документ. А с модулем кнопки — тяжелее. Ну и с самой кнопкой — нарисуйте встроенными инстр-ми фигуру (или обьект WordArt) что Вам нравится, и назначьте ей нужную процедуру (правая кнопка > Назначить макрос (или как там у Вас по локализации)). Всего пару кликов. И практично, и веселее, и проще, а не унылая серость.
А про «…регулярные выражения…«. Что Вы имели ввиду? Я их там не вижу.

Добавлено через 25 минут
Кажется, я понял про регулярку. Смотрите, у Тoiai грамотный и лаконичный код. Лично я бы все-таки сгенерированный массив выгрузил на лист, чтоб было видно. I.e., после next я бы добавил строку:

[a1].resize(1, ubound(a)).value=a

Дальше он вызывает окно сообщения MsgBox, в котором использует фукции не VBA, а Excel — Min и Max. Поэтому его тяжелая жизнь заставила вызывать их такими фразами Application.Max(a), Application.Min(a)…
Кстати, что б, если не нужно, не выкладывать массив на лист, его тоже можно одним движение загнать в этот же MsgBox.

Понравилась статья? Поделить с друзьями:
  • Vba excel методы ячейки
  • Vba excel методы строки
  • Vba excel методы массивов
  • Vba excel метод гаусса
  • Vba excel метод sort как