我有这个宏
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim x As Integer
Dim S1 As String
Dim S2 As String
S1 = "Football"
S2 = "Basket"
x = 1
Do
If IsEmpty(Cells(x, 5)) And ((Cells(x, 3) = S1) Or (Cells(x, 3) = S2)) Then
MsgBox "Insert a value in the empty cell"
Cancel = True
End If
x = x + 1
Loop Until Cells(x, 1) = ""
End Sub
当我单击“x”按钮关闭工作表时,如果第5列为空并且3列包含Football
或Basket
,则宏会生成一个控件并显示一个消息框以提醒你插入了一个值。检查结果但我不知道MsgBox
出现16次而不是1.为什么?
答案 0 :(得分:2)
将我的评论写入答案。添加更多内容。
LONG
sheet1
中检查单元格,但在关闭工作簿时sheet2
处于活动状态,则无法获得所需的结果MsgBox
中的留言更有意义。用户将如何知道哪个单元格为空:)这是你在尝试什么? (的 UNTESTED 强>)
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim S1 As String, S2 As String
Dim lRow As Long, i As Long
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
S1 = "Football": S2 = "Basket"
With ws
'~~> Find the last row which has data
'~~> we will loop till there
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 1 To lRow
If Len(Trim(.Range("E" & i).Value)) = 0 Then
Select Case .Range("C" & i).Value
Case S1, S2
'~~> Tell user which cell is empty
MsgBox "Insert a value in the cell " & _
.Range("E" & i).Address
Cancel = True
'~~> Exit the loop after the first match
Exit For
End Select
End If
Next i
End With
End Sub