VBA rounding to nearest by arraylist

Nervatos

New Member
Joined
Dec 19, 2021
Messages
32
Office Version
  1. 365
Platform
  1. Windows
  2. Mobile
Hello everyone

I have found a vba script to find the nearest value, but I need it to find the nearest value like round up

VBA Code:
Sub Demo()
    Dim numbers(), arrItem, maxItem, result, searchNum

    searchNum = 0
    numbers = Array(0.75, 1.5, 2.5, 4, 6, 10, 16, 25, 35, 50, 70, 95, 120, 150, 185, 240, 300)
    maxItem = Application.Max(numbers)
    
    For Each arrItem In numbers
        If Abs(searchNum - arrItem) < maxItem Then
            maxItem = Abs(searchNum - arrItem)
            result = arrItem
        End If
    Next arrItem
    Debug.Print result       
End Sub

So value 1 would be to 1.5, 1.5 like 1.5, 2.6 would be 4 ect.
Right now, value 1 going to 0.75, but should be 1.5.


Hope some can fix it for me.

Merry Christmas.
 

Excel Facts

Format cells as time
Select range and press Ctrl+Shift+2 to format cells as time. (Shift 2 is the @ sign).
See if this code does what you want

VBA Code:
Sub Demo1()
    Dim numbers(), arrItem, result, searchNum

    searchNum = 2.6
    numbers = Array(0.75, 1.5, 2.5, 4, 6, 10, 16, 25, 35, 50, 70, 95, 120, 150, 185, 240, 300)
    
    If searchNum > Application.Max(numbers) Then
        result = "Not found"
    Else
        For Each arrItem In numbers
            If arrItem >= searchNum Then
                result = arrItem
                Exit For
            End If
        Next arrItem
    End If
    Debug.Print result
End Sub

Hope this helps

M.
 
Upvote 0
Solution
Hello Marcelo

It was exactly as it was supposed to do. Thank you so much!
Merry Christmas.
 
Upvote 0

Forum statistics

Threads
1,213,563
Messages
6,114,332
Members
448,566
Latest member
Nickdozaj

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