当我尝试在工作簿更改事件中为每个循环运行两个时,仅执行第二个循环,并且MSGBox窗口可重复弹出,而不是关闭。我如何找到一个有利的解决方案?请参阅以下代码。
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Set a = Worksheets("first").Range("q2:q417")
' first foreachloop
-------------------
For Each b In a
If b.Value <> "" And Not IsDate(b) Then
b.ClearContents
MsgBox ("please enter valid date")
End If
Next b
'second foreach loop
--------------------
Set c = Worksheets("first").Range("s2:s417")
For Each C In a
If C.Value <> "A" Or _
C.Value <> "B" Or _
C.Value <> "EF" Or _
C.Value <> "CE" Then
C.ClearContents
MsgBox ("PLEASE ENTER VALID STATUS")
End If
Next C
End Sub
我的理解是,您正在尝试监视指定范围Uppon更改的单元格内容。
因此:
a(您需要将Worksheet_SelectionChange
事件更改为Worksheet_Change
。
b(您需要检查哪个单元格被更改,如果是指定范围的,请验证其内容。
将代码下面放在"第一"纸后面的模块中。
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim a As Range
Set a = Range("q2:q417")
If Not Intersect(Target, a) Is Nothing Then
With Target
If Not IsEmpty(.Value) And Not IsDate(.Value) Then
.ClearContents
MsgBox "please enter valid date"
End If
End With
End If
Dim b As Range
Set b = Range("s2:s417")
If Not Intersect(Target, b) Is Nothing Then
With Target
If Not IsEmpty(.Value) Then
If .Value <> "A" And _
.Value <> "B" And _
.Value <> "EF" And _
.Value <> "CE" Then
.ClearContents
MsgBox "PLEASE ENTER VALID STATUS"
End If
End If
End With
End If
End Sub