简体   繁体   中英

Excel VBA find maximum value in range on specific sheet

I found that the following code is getting max value in range:

Cells(Count, 4)=Application.WorksheetFunction.Max(Range(Cells(m, 1),Cells(n, 1)))

How can I search within a specific sheet? Data sheet in this case

Like:

Worksheets(d).Cells(x, 4).Value = Worksheets("Data")... ????? FIND MAX ????

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

You can pass any valid excel cell reference to the range method as a string.

Application.WorksheetFunction.Max(range("Data!A1:A7"))

In your case though, use it like this, defining the two cells at the edges of your range:

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

If you want to process quickly milion of cells to find MAX/MIN, you need heavier machinery. This code is faster then Application.WorksheetFunction.Max .

Function Max(ParamArray values() As Variant) As Variant
   Dim maxValue, Value As Variant
   maxValue = values(0)
   For Each Value In values
       If Value > maxValue Then maxValue = Value
   Next
   Max = maxValue
End Function

Function Min(ParamArray values() As Variant) As Variant
   Dim minValue, Value As Variant
   minValue = values(0)
   For Each Value In values
       If Value < minValue Then minValue = Value
   Next
   Min = minValue
End Function

Stolen from here: https://www.mrexcel.com/forum/excel-questions/132404-max-min-vba.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM