Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Max of a column in VBA

Tags:

max

vba

I am trying to find the max value of a cell within A2 to A999. I tried to do a For Loop to loop through each one, but having problems with the logic to find the max rcell. I was hoping there was a built-in rcell.max function?

Set rng = loopset.range("A2-A999")
For Each rcell in rrng.cells
'Find the max rcell
Next rcell
like image 514
nas Avatar asked Mar 06 '17 18:03

nas


People also ask

How do I find the maximum rows in excel VBA?

The maximum number of rows is 1,048,576 for every sheet in excel (this might depend on your version).

What is VBA Worksheetfunction?

Worksheet function in VBA is used when we have to refer to a specific worksheet, normally when we create a module the code executes in the currently active sheet of the workbook but if we want to execute the code in the specific worksheet we use worksheet function, this function has various uses and applications in VBA ...

Can you pass function as parameter in VBA?

You can't actually pass functions in VBA unfortunately and OpenPulledReports() thinks it is getting passed 2 values.


2 Answers

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 
like image 21
Yoav24 Avatar answered Oct 08 '22 19:10

Yoav24


Application.worksheetfunction.max(range("a:a")) will do it for you

like image 51
nwhaught Avatar answered Oct 08 '22 19:10

nwhaught