Excel : Data Validation, how to force the user to enter a string that is 2 char long?

后端 未结 6 1031
梦谈多话
梦谈多话 2021-01-14 23:56

I would like to add some data validation on a cell in the latest Excel. I would like to force the user to enter a string that is two-char long, with the first char a digit,

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-15 00:03

    Here's an overkill method, literally just for fun (don't downvote me for having a little fun with VBA - this is actually useful to know how to do). It adds a data validation list to a range that only allows a number followed by an uppercase letter. I do this by quite literally adding every single combination allowable :) Of course you don't have to SELECT form the list, but if you try to type something that's not allowed, you get the buzzer :)

    Sub AddValidation()
    
    Dim cell As Range
    Dim dict As Object
    Set dict = CreateObject("scripting.dictionary")
    Dim alphabet As String, numbers As String
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    numbers = "1234567890"
    Dim validList As String
    
    For i = 1 To Len(numbers)
        For j = 1 To Len(alphabet)
            dict.Add Mid$(numbers, i, 1) & Mid$(alphabet, j, 1), 1
        Next
    Next
    
    validList = Join(dict.keys, ", ")
    
    'Example using B1:B10
    With Range("B1:B10").Validation
        .Delete
        .Add Type:=xlValidateList, _
        AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:=validList
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = "Invalid data entered"
        .ShowInput = True
        .ShowError = True
    End With
    
    End Sub
    

提交回复
热议问题