excel中宏控制中的循环错误

时间:2013-09-12 07:59:11

标签: excel vba excel-vba

我有这个宏

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列包含FootballBasket,则宏会生成一个控件并显示一个消息框以提醒你插入了一个值。检查结果但我不知道MsgBox出现16次而不是1.为什么?

1 个答案:

答案 0 :(得分:2)

将我的评论写入答案。添加更多内容。

  1. 声明您的变量/对象。你不会容易出错。如果您正在使用Excel中的行,最好将它们声明为LONG
  2. 完全限定您的对象。例如哪个细胞和哪个表?如果要在sheet1中检查单元格,但在关闭工作簿时sheet2处于活动状态,则无法获得所需的结果
  3. 您正在收到多条消息,因为循环一直持续到找到所有匹配项。在第一场比赛后退出循环
  4. MsgBox中的留言更有意义。用户将如何知道哪个单元格为空:)
  5. 这是你在尝试什么? (的 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