validation用户input

我试图运行一个marco,检查用户input的单元格,并确保它们不是空白的。 我对一个单元格很难。 我希望用户被限制进入只有2个字母,我希望它检查,以确保没有号码input该单元格,否则抛出一个错误消息,并退出子。 任何帮助是极大的赞赏!

If Worksheets("New PN").Range("B12").Value = "" Then MsgBox "Date cannot be left empty.", vbOKOnly + vbExclamation, "Entry Error" Exit Sub End If 

试试这个!

 cellContent = Worksheets("New PN").Range("B12").Value leftCC = Left(cellContent, 1) rightCC = Right(cellContent, 1) If Len(cellContent) <> 2 Then MsgBox "There needs to be 2 characters." Exit Sub ElseIf (Asc(leftCC) < 65 Or Asc(leftCC) > 122 _ Or (Asc(leftCC) > 90 And Asc(leftCC) < 97)) _ Or _ (Asc(rightCC) < 65 Or Asc(rightCC) > 122 _ Or (Asc(rightCC) > 90 And Asc(rightCC) < 97)) Then MsgBox "Both characters can only be letters." Exit Sub End If 

可能是大而可怕的,但它会完成100%的工作。

编辑: Asc(char)公式返回所提供的字符的ASCII码。 az和AZ的外部限制是65和122,但是一些非字符包含在中间(即[,\,],^,_,`)。 因此,可怕的,如果。

尝试这个:

 my_string = Worksheets("New PN").Range("B12").Value If Len(my_string) = 2 And Left(my_string, 1) Like "[A-Za-z]" _ And Right(my_string, 1) Like "[A-Za-z]" Then '~~execute what you want here Else MsgBox "Invalid input" & vbNewLine & "Enter 2 LETTERS only" End If 

希望这可以帮助。