Max number finder in VBA

Alcat03

New Member
Joined
Nov 7, 2023
Messages
7
Office Version
  1. 365
Platform
  1. Windows
I am trying to find the max number using a loop. I do not want to use the application function. I want to use a loop, but can't figure it out. I have a reset button that generates 20 numbers out of 100 and a separate button that will output the max number out of the random 20 numbers. This is what i have so far.

Sub Button_Reset()
Dim i As Integer
Cells.Clear
For i = 1 To 20
Cells(i, 1) = Application.RandBetween(1, 100)
Next i

End Sub

Sub Button_Max()
Dim rng As Range
Dim max As Integer
Set rng = Range("1:20")
For i = 1 To 100

Next i

MsgBox ("The max is " & max & ".")

End Sub
 

Excel Facts

Control Word Wrap
Press Alt+Enter to move to a new row in a cell. Lets you control where the words wrap.
How about this?

VBA Code:
Sub Button_Max()
Dim max As Integer
Dim rng As Range: Set rng = Range("A1:A20")
Dim AR() As Variant:    AR = rng.Value2

For i = 1 To UBound(AR)
    If AR(i, 1) > max Then max = AR(i, 1)
Next i

MsgBox ("The max is " & max & ".")

End Sub
 
Upvote 0
You can take advantage of the cycle you use to put the random numbers:


VBA Code:
Sub Button_Reset()
  Dim i As Integer, nMax As Long
  Cells.Clear
  For i = 1 To 20
    With Cells(i, 1)
      .Value = Application.RandBetween(1, 100)
      If .Value > nMax Then nMax = .Value
    End With
  Next
  MsgBox ("The max is " & nMax & ".")
End Sub
 
Upvote 0

Forum statistics

Threads
1,215,073
Messages
6,122,975
Members
449,095
Latest member
Mr Hughes

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top