Using Excel 2010. I want to only allow values in a cell that fit a given regex pattern. So I created a UDF module as follows:
Public re as RegExp
Public Function isValidRegex(rng As Range, pattern As String) As Boolean
If re Is Nothing Then
Set re = New RegExp
End If
re.pattern = pattern
isValidRegex = re.Test(rng.value)
End Function
I created a named range called THIS_CELL, so that the current cell can be passed to isValidRegex(), as follows:
=INDIRECT(ADDRESS(ROW(),COLUMN()))
I set a custom validation for the cell, using this formula:
=isValidRegex(THIS_CELL,"(my|regex)patt[ern]")
This generated the following error:
A named range you specified cannot be found.
According to this article, UDFs cannot be used in Custom validation formulas. The solution suggested in the article (putting the formula in another cell, making that cell into a named range, and referencing that cell in the Custom formula) won't work, because I need to be able to pass THIS_CELL as an argument to the function.
I also tried creating a named range called isValidRegexPattern, defining it as =isValidRegex(THIS_CELL,"(my|regex)patt[ern]"), and setting the Custom formula to =isValidRegexPattern, but this didn't work either; putting a breakpoint in isValidRegex() showed that the function wasn't even being called.
So, how can I use a UDF for cell validation?


Worksheet_SelectionChangewill catch the pre-change value of B1, but not B2:B5, and because it's a VBA call, Undo won't retrieve the previous values. Or am I missing something?Worksheet_Changeevent that would work for youLikeoperatorWorksheet_Changedoesn't capture the pre-change state of the cell, as I said in my comment to brettdj. As for RegEx complexity, there are several patterns that involve repeated capturing groups, e.g. "^(\d{3}(,|$))+". These are somewhat complicated to express withLike, and would probably each require their own VBA string-processing algorithm if we don't use Regex.