Search code examples
excelconditional-statementsblank-line

Excel: use previous value if condition not met, ignoring blanks


I'm trying to match data with IF and vlookup but can't seem to get it to work. Task is:

Row 1    A    B      C        D
Row 2    1    251    8:00:00    
Row 3    2    253    
Row 4    1    252    
Row 5    2    254    8:00:01  
Row 6    1    257       
Row 7    2    250    8:00:02
Row 8    3    260    
Row 9    4    248    
Row 10    1    255    8:00:03

If column C has value, then I want to subtract column A with previous row in column A, if current row is less than previous, I want to record the corresponding column B value in column D. If false, then find the previous valid cell in column B such that current A is less than previous A, and record in D. If column C has no value, then leave blank.

Example: C2 has value, but there is no data before it, hence D2 is blank. C5 has value, A5 > A4, hence we try to find previous value until we find A4 < A3, and we record the value of B4 (ie 252) in D4. C10 has value, A10 < A9, and we record B10 (ie 255) in D10.

Row 1    A    B      C        D
Row 2    1    251    8:00:00    
Row 3    2    253    
Row 4    1    252    
Row 5    2    254    8:00:01  252
Row 6    1    257       
Row 7    2    250    8:00:02  257
Row 8    3    260    
Row 9    4    248    
Row 10    1    255    8:00:03 255

Solution

  • To achieve this, I would:

    1. Insert a new column between existing A and B columns
    2. In cell B2 put the formula =B1+IF(A2<A1,1,0) and copy this formula down for as many entries in column B as you need
    3. In cell E3 (don't bother starting in E2 because you know you want this cell to be blank) put the formula =IF(D3&""<>"",VLOOKUP(MAX($B$2:B3),B:C,2,FALSE),"")
    4. Copying E3 down should give you the result you're after.