Consulting

Results 1 to 5 of 5

Thread: Solved: Find row above and below searchvalue, VBA

  1. #1
    VBAX Tutor
    Joined
    Jan 2008
    Posts
    266
    Location

    Solved: Find row above and below searchvalue, VBA

    Hi.

    Lets say I have a column with the following values.

    A1 2
    A2 4
    A3 6
    A4 8
    A5 10

    And the user inputs "5".
    How can I write a code that gives me two variables called for example "above" and "below" with the rownumbers 2 and 3.
    I know for sure the value the user inputs does not excist (all values in the column have decimals).

  2. #2
    Moderator VBAX Guru Simon Lloyd's Avatar
    Joined
    Sep 2005
    Location
    UK
    Posts
    3,003
    Location
    You dont need code just some vlookups, example:
    =vlookup(B1,A:A,1,TRUE)
    usually you'd use FALSE as the type of search but in this case using TRUE will find the nearest value without going over the specified value, modifying one or two of these would work for you
    Regards,
    Simon
    Please read this before cross posting!
    In the unlikely event you didn't get your answer here try Microsoft Office Discussion @ The Code Cage
    If I have seen further it is by standing on the shoulders of giants.
    Isaac Newton, Letter to Robert Hooke, February 5, 1675 English mathematician & physicist (1642 - 1727)

  3. #3
    VBAX Tutor
    Joined
    Jan 2008
    Posts
    266
    Location
    I do need the code.
    It will be part of a big code.


    Edit: but thanks for the alternative

  4. #4
    Administrator
    VP-Knowledge Base
    VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    Assuming your data is in ascending order

    [VBA]Sub Test()
    Dim x As Single, y As Long
    Dim r As Range

    Set r = Range("Data")
    x = InputBox("Enter Value")
    y = Application.Match(x, Range("Data"), 1)

    MsgBox r(y) & ", " & r(y + 1)

    End Sub[/VBA]
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

  5. #5
    VBAX Tutor
    Joined
    Jan 2008
    Posts
    266
    Location
    Quote Originally Posted by mdmackillop
    Assuming your data is in ascending order

    [vba]Sub Test()
    Dim x As Single, y As Long
    Dim r As Range

    Set r = Range("Data")
    x = InputBox("Enter Value")
    y = Application.Match(x, Range("Data"), 1)

    MsgBox r(y) & ", " & r(y + 1)

    End Sub[/vba]


    No, it was in decending order. Never thought about that.
    Just wrote the post on my phone last night.

    But thatnks for the code I managed to get it working.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •