[英]Wrong cycle in macro control in excel
I have this macro 我有这个宏
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
When i click the "x" button to close the sheet if the column 5 is empty and the 3 column contains Football
or Basket
the macro makes a control and appear a Message box to alert that you have insert a value. 当第5列为空并且第3列包含
Football
或Basket
时,我单击“ x”按钮关闭工作表时,宏将进行控制并显示消息框,提示您已插入值。 The check goes but i don't know the MsgBox
appears 16 times and not 1. Why? 检查成功了,但我不知道
MsgBox
出现了16次而不是1次。为什么?
Putting my comments into an answer. 将我的评论放入答案。 Adding more things as well.
以及添加更多的东西。
LONG
LONG
sheet1
but sheet2
is active when you are closing the workbook then you will not get the desired results sheet1
的单元格,但在关闭工作簿时sheet2
处于活动状态,那么您将无法获得预期的结果 MsgBox
more meaningful. MsgBox
的消息更有意义。 How will the user know which cell is empty :) Is this what you are trying? 这是您要尝试的吗? ( 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.