My code sets list validation on a cell using the range given by an OFFSET formula that depends on that cell’s address.
Because this validation gets set programmatically on cells that already have contents, I want a function to determine whether the existing contents of the cell violate validation.
I ran into problems testing this, using the following code:
Sub test()
Dim sht As Worksheet
Dim rng As Range
Dim formula As String
Dim rangeName As String
Set sht = ThisWorkbook.Sheets("Sheet1")
With sht
.Range("a1").Value = "a"
.Range("a2").Value = "aa"
Set rng = .Range("b1")
formula = "=OFFSET(INDIRECT(ADDRESS(ROW(),COLUMN())),0,-1,2,1)"
rng.Validation.Add Type:=xlValidateList, Formula1:=formula
rangeName = Replace(formula, "=", "")
Set ResultRange = .Range(rangeName).Find(rng.Value, lookat:=xlWhole)
If ResultRange Is Nothing Then
Debug.Print "violates validation"
Else
Debug.Print "validated"
End If
End With
End Sub
This test should assign drop-down validation to cell B1 with the contents of cells A1 and A2, then check whether or not B1‘s contents match either of those cells. But it fails at the Set ResultRange line with this error:
Method 'Range' of object '_Global' failed.
I think the problem is that when I call Range(rangeName), Excel doesn’t know which cell to apply the ROW() and COLUMN() to, so I need to somehow calculate the address that formula resolves to for this cell–in this case, $A$1:$A$2, so that I can assign that value to RangeName.
So, given this OFFSET() formula that I’m passing dynamic parameters to, how do I get the range that this formula returns for the range specified by rng?
EDIT: As the formula may change depending on different circumstances, I’m looking for a solution that, given an OFFSET() formula starting at a certain range, returns the range given by that formula. A hard-coded solution would not be acceptable, as there are several different OFFSET() formulas like this in the sheet and it will be impractical to change the code of the validation test every time one of the formulas changes.
This isn’t pretty, but will do what you like you must have already defined
rng, andrngmust not be in column A:As another note, your validation will by default ignore blanks so you may want to update your if to check for blanks:
EDIT as requested, I went ahead and made the OffsetFormula optional because it will assume the passed range has the formula that needs parsed: