Home » excel » vba – If-then / Select Case for date range defined in cell reference

vba – If-then / Select Case for date range defined in cell reference

Posted by: admin May 14, 2020 Leave a comment

Questions:

I apologize for the newb question but have not found a solution online. I am trying to do a simple if-then statement on date ranges in VBA. My code (not working) thus far:

            LR = 52
            Set rngData = Range("D2:D" & LR)
            'define the data range to evaluate
            For Each rngCell In rngData
                Select Case rngCell.Value
                    Case Val(Range("'Some_dates'!O8").Value) To Val(Range("'Some_dates'!P8").Value): rngCell.Value = Range("'Some_dates'!N8").Value
                    Case Val(Range("'Some_dates'!O9").Value) To Val(Range("'Some_dates'!P9").Value): rngCell.Value = Range("'Some_dates'!N9").Value
                    Case Val(Range("'Some_dates'!O10").Value) To Val(Range("'Some_dates'!P10").Value): rngCell.Value = Range("'Some_dates'!N10").Value
                    Case Val(Range("'Some_dates'!O11").Value) To Val(Range("'Some_dates'!P11").Value): rngCell.Value = Range("'Some_dates'!N11").Value
                Case Else: rngCell.Value = "Outside date ranges"
                End Select
            Next rngCell

The output for all the cells is “Outside date ranges”, which means it is choosing the “else” value for all the cells in rngData, which is incorrect.

Cells O8:P11 in the ‘Some_dates’ worksheet define four date ranges (start is column O and end is column P). These are dates that can look like numbers or dates depending on how you format the cell. Column N in the ‘Some_dates’ worksheet has labels for each date range.

Any help is appreciated!

How to&Answers:

If everything you are comparing is dates, then Val is the problem. Val(1/1/2012), where 1/1/2012 is a “real” Excel date (or a fake one for that matter) returns “1”. Val returns the beginning of a string up to the first non-numeric character. So, try:

Case Range("'Some_dates'!O8").Value To Range("'Some_dates'!P8").Value: rngCell.Value = Range("'Some_dates'!N8").Value

Your code should work when the dates are stored in General or Number format, as then Val returns the entire number (string).