我想限制A列和D列中的用户输入。
在A栏中,用户应输入值R00yyyyyy
,其中yyyyyy是介于000000和999999之间的数字。
在D栏中,他们只能输入y
或n
。
下面的代码似乎无法正常工作。 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
答案 0 :(得分:3)
假设您的其余代码是正确的,您需要将逻辑测试从Or更改为And
If b <> "y" And b <> "n" Then
MsgBox ("The only allowable entry here is Y or N")
End If
答案 1 :(得分:2)
你有这一行
If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub
因此,当他们更改D列中的任何内容时,它不在A中,代码会在到达D代码之前退出
答案 2 :(得分:0)
您可以尝试以下代码。它会检查更改是否在A 或列D列中,如果两列都没有更改,则会退出。
然后您知道更改位于A列或D列中,并确切地检查哪个列。然后根据输入进行相应的检查并显示相应的消息框。
要检查R00yyyyyy
这样的简单模式,其中y
是一个数字,您可以使用Like
运算符并使用#
作为占位符来表示&#39; any数&#39;
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