1

我有这个宏

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。为什么?

4

1 回答 1

2

将我的评论放入答案中。也添加更多的东西。

  1. 声明你的变量/对象。您将不太容易出错。如果您在 Excel 中处理行,最好将它们声明为LONG
  2. 完全限定您的对象。例如哪些单元格和哪个工作表?如果您想签入单元格sheet1sheet2在关闭工作簿时处于活动状态,那么您将无法获得所需的结果
  3. 随着循环继续进行,直到找到所有匹配项,您将收到多条消息。第一场比赛后退出循环
  4. 让您的讯息MsgBox更有意义。用户如何知道哪个单元格是空的:)

这是你正在尝试的吗?(未经测试

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
于 2013-09-12T08:21:57.193 回答