Home » excel » excel – How do i edit this VBA code to accept different values?

excel – How do i edit this VBA code to accept different values?

Posted by: admin May 14, 2020 Leave a comment

Questions:

Having some trouble getting this online copypasta working correctly. First character must be A to Z, second character 1 to 5, third character “” or 0 to 9.

Box function is to specify a cell in Range A1:Z53.

Ideas on syntax?

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii
    Case Asc("0") To Asc("9")
    Case Asc("-")
        If Instr(1,Me.TextBox1.Text,"-") > 0 Or Me.TextBox1.SelStart > 0 Then
            KeyAscii = 0
        End If
    Case Asc(".")
        If InStr(1, Me.TextBox1.Text, ".") > 0 Then
            KeyAscii = 0
        End If
    Case Else
        KeyAscii = 0
End Select
End Sub
How to&Answers:

Thanks, but I got a good tip to use RegEx. This ended up being the best solution for my application. After searching i found a previous answer that just needed the following modification to work in this scenario:

.IgnoreCase = False

.Pattern = "[A-Z]([1-9]|[1-4][0-9]|[5][0-3])$"

Code can be found here:
Apply Regex into a textbox form VBA

Answer:

VBA has limited pattern matching using the Like operator :

IsInRange = text Like "[A-Z][1-9]" Or text Like "[A-Z][1-4][0-9]" Or text Like "[A-Z]5[0-3]"

Another alternative can be using the Excel intersect method (will also work with for example “$Z$53“) :

IsInRange = Not Intersect([A1:Z53], Range(text)) Is Nothing

or Excel range intersect operator :

IsInRange = Not Evaluate("ISERR(A1:Z53 " & text & ")")