如何限制用户在单个列中仅输入 "Y" 或 "N"

How to restrict user to entering only "Y" or "N" in a single column

我想在 A 列和 D 列中限制用户输入。

在 A 列中,用户应输入 R00yyyyyy 的值,其中 yyyyyy 是介于 000000 和 999999 之间的数字。

在 D 列中,他们应该只输入 yn

我的以下代码似乎无法正常工作。 A 列部分工作正常,只是 D 列有问题。

任何人都可以建议一种方法来限制 D 列中的条目吗?

Private Sub Worksheet_Change(ByVal Target As Excel.Range)

Dim rngCell As Range

If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub

Application.EnableEvents = False
For Each rngCell In Target.Cells
    rngCell = UCase(rngCell)
    If rngCell.Characters.Count > 9 Then
    MsgBox ("Student number too long")
    rngCell.Clear
    End If
   If Not IsEmpty(rngCell.Value) Then
    Dim s As String
    Dim s1 As String
    Dim y As String
    Dim y1 As String
    s = CStr(rngCell.Value)
    s1 = Left(s, 3)
    y = CStr(rngCell.Value)
    y1 = Right(y, 6)
    If s1 <> "R00" Or Not IsNumeric(y1) Then
    MsgBox ("Must be in the form R00yyyyyy, where yyyyyy is a number between 000000 and 999999")
    rngCell.Clear
    End If
   Else
   End If
Next
Application.EnableEvents = True

Dim rngCell2 As Range

If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub

Application.EnableEvents = False
For Each rngCell2 In Target.Cells
    rngCell2 = UCase(rngCell2)
    Dim b As String
    b = CStr(rngCell2.Value)
    If b <> "y" Or b <> "n" Then
    MsgBox ("The only allowable entry here is Y or N")
    End If
Next
Application.EnableEvents = True

End Sub

假设您的其余代码是正确的,您需要将逻辑测试从 Or 更改为 And

If b <> "y" And b <> "n" Then
    MsgBox ("The only allowable entry here is Y or N")
End If

你有这条线

 If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub

因此,当他们更改 D 列中的任何内容时,它不在 A 中,并且代码在到达 D 的代码之前退出

您可以试试下面的代码。它检查更改是否在 A 列 或 D 列 中,如果两列都没有更改则退出。

然后您知道更改是在 A 列还是 D 列中,并检查到底是哪一列。然后根据输入进行适当的检查并显示适当的消息框。

要检查像 R00yyyyyy 这样的简单模式,其中 y 是一个数字,您可以使用 Like 运算符并使用 # 作为 [=24 的占位符=].

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim rngCell As Range

    ' exit if change was not in column A and not in column D
    If Intersect(Target, Range("A:A,D:D")) Is Nothing Then Exit Sub

    ' get first cell of change
    Set rngCell = Target.Cells(1, 1)

    ' disable events
    Application.EnableEvents = False

    ' now check if change in column A
    If rngCell.Column = 1 Then
        If Not rngCell.Value Like "R00######" Then
            MsgBox "Must be in the form R00yyyyyy, where yyyyyy is a number between 000000 and 999999"
            rngCell.Clear
        End If
    Else 'must have been in column D
        If rngCell.Value <> "y" And rngCell.Value <> "n" Then
            MsgBox "The only allowable entry here is Y or N"
            rngCell.Clear
        End If
    End If

    ' re-enable events
    Application.EnableEvents = True

End Sub