Roderick_E
Well-known Member
- Joined
- Oct 13, 2007
- Messages
- 2,051
So I created some VBA to loop through either a direct manually input data validation set or a named range and automatically pick the entry that matches the string a user types in.
For example, say you had a list of U.S. state names and the user starts typing New y and presses enter, it would return New York since that would be in the list.
The problem I'm having is that worksheet change is continuing to trigger and gets stuck in a recursive loop. Can someone suggest changes to my code? Thanks
(P.S. turn off data validate error alert for it to work) Keep in mind if you test this as it you will also get stuck in the loop. ctrl+break to get out.)
For example, say you had a list of U.S. state names and the user starts typing New y and presses enter, it would return New York since that would be in the list.
The problem I'm having is that worksheet change is continuing to trigger and gets stuck in a recursive loop. Can someone suggest changes to my code? Thanks
(P.S. turn off data validate error alert for it to work) Keep in mind if you test this as it you will also get stuck in the loop. ctrl+break to get out.)
Code:
Option Compare Text 'ignore text case
Private Sub Worksheet_Change(ByVal Target As Range)
Dim str As String
Dim strarray As String
Dim strunbound() As String
Dim i As Long
Dim noff As Long 'noff = no freeform, set to 1 if you don't want to allow freeform input
noff = 1
If IsNumeric(Target.SpecialCells(xlCellTypeSameValidation).Cells.Count) Then
If Trim(Target) = "" Then
Exit Sub
End If
strarray = Target.Validation.Formula1
If InStr(strarray, "=") > 0 Then
str = Replace(strarray, "=", "")
strarray = "" 'reset
For Each c In Range(Application.ActiveWorkbook.Names(str).RefersTo)
strarray = strarray & c & ","
Next c
strarray = Left(strarray, Len(strarray) - 1) 'to delete trailing comma
End If
strunbound = Split(strarray, ",")
For i = LBound(strunbound) To UBound(strunbound)
If InStr(strunbound(i), Target) > 0 Then
Target.Value = strunbound(i)
Exit Sub
End If
Next i
If noff = 1 Then
strarray = Target
Target.Value = ""
'Target.Select
MsgBox strarray & " does not match in list.", vbCritical, "ERROR"
Exit Sub
End If
End If
End Sub