Finding next greater value in unsorted column with VBA

TheWolf

New Member
Joined
May 1, 2021
Messages
2
Office Version
  1. 2019
Platform
  1. Windows
Hello

I have X and Y coordinates stored in two columns. I want to enter an X and Y coordinate in to my Userform and get the closest, greater X coordinate with the same Y value.
I thought this would be easy, but I can’t figure out how to do this.

A simplified Example:
If I enter Y =3 and X =35 (Row 6) in to the textboxes in the userform, I would like a msgbox with the value 60 (row 12).

Example.PNG


Grateful for all ideas.
Thanks in advance

Ulf
 

Excel Facts

Format cells as currency
Select range and press Ctrl+Shift+4 to format cells as currency. (Shift 4 is the $ sign).
I haven't done this with a Userform, but see if you can adapt this.

TheWplf.xlsm
ABCDE
1YXY3
2275X35
3330
4110
5540
6335
7245
8365
9520
10150
11255
12360
13370
14525
15315
16
Sheet1


VBA Code:
Sub Get_Next()
  Dim SL As Object
  Dim a As Variant
  Dim i As Long
  Dim Yval As Double, Xval As Double
  
  Set SL = CreateObject("System.Collections.SortedList")
  a = Range("A2", Range("B" & Rows.Count).End(xlUp)).Value
  Yval = Range("E1").Value
  Xval = Range("E2").Value
  For i = 1 To UBound(a)
    If a(i, 1) = Yval And a(i, 2) > Xval And Not SL.Containskey(a(i, 2)) Then SL.Add a(i, 2), i
  Next i
  If SL.Count > 0 Then
    MsgBox SL.GetKey(0)
  Else
    MsgBox "No greater value"
  End If
End Sub
 
Upvote 0
Solution
Thank you for taking the time.

I think I will manage to tweak your code a little bit to suit my needs.

Thanks again, for your help!

Ulf
 
Last edited by a moderator:
Upvote 0
You're welcome. Thanks for the follow-up.
 
Upvote 0

Forum statistics

Threads
1,214,649
Messages
6,120,732
Members
448,987
Latest member
marion_davis

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