简体   繁体   English

Excel中的宏控制周期错误

[英]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列包含FootballBasket时,我单击“ 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. 以及添加更多的东西。

  1. Declare your variables/objects. 声明变量/对象。 You will be less prone to errors. 您将不太容易出错。 If you are working with rows in Excel, it is better to declare them as LONG 如果要在Excel中处理行,最好将它们声明为LONG
  2. Fully qualify your objects. 完全限定您的对象。 For example which cells and in which sheet? 例如,哪个单元格在哪个工作表中? If you want to check the cells in sheet1 but sheet2 is active when you are closing the workbook then you will not get the desired results 如果要检查sheet1的单元格,但在关闭工作簿时sheet2处于活动状态,那么您将无法获得预期的结果
  3. You are getting multiple messages as the loop keeps on going till it finds all matches. 随着循环不断进行,直到找到所有匹配项,您将收到多条消息。 Exit the loop after the first match 第一场比赛后退出循环
  4. Make your Message in the 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM