MsgBox适用于一系列单元格

时间:2018-03-28 11:00:33

标签: excel vba excel-vba

如果列G的单元格中的内容不等于0,我尝试创建显示MsgBox的代码。代码仅适用于一个单元格,但不适用于整个范围(G20:G100)。 你能帮忙吗? 感谢

Private Sub Worksheet_Calculate()

If Sheets("Sheet1").Range("G20:G100").Value <> 0 Then
    MsgBox "Not equal to 0", vbOKOnly
End If

End Sub

2 个答案:

答案 0 :(得分:2)

试试这样:

Private Sub Worksheet_Calculate()

    Dim myCell As Range

    For Each myCell In Range("G20:G100")
        If myCell <> 0 Then
            MsgBox myCell.Address & " is not equal to 0", vbOKOnly
            Exit Sub
        End If
    Next myCell        
End Sub

它会检查范围内的每个单元格。对于找到的第一个单元格,其值不同于0,它会为MsgBox提供其地址并退出。

您可以使MsgBox更具信息性,显示单元格的当前值,如下所示:

MsgBox myCell.Address & " is " & myCell.Text, vbOKOnly

如果您移除Exit Sub,则会为不同于MsgBox的每个单元格显示不同的0 - 。

答案 1 :(得分:2)

下面的代码稍长一些,但您会在1个摘要MsgBox中得到结果,其中包含Range("G20:G" &LastRow)<>0的所有单元格的列表。

<强>代码

Private Sub Worksheet_Calculate()

    Dim myCell As Range, LastRow As Long
    Dim MsgString As String

    LastRow = Cells(Rows.Count, "G").End(xlUp).Row ' get last row with data in Column G
    ' making sure there is at least 1 cell with data in it below "G20"
    If LastRow < 20 Then
        MsgBox "Your range from G20 and below is empty", vbCritical
        Exit Sub
    End If

    For Each myCell In Range("G20:G" & LastRow)
        If myCell.Value <> 0 Then
            If MsgString <> "" Then  ' not first cell which is <> 0
                MsgString = MsgString & vbCr & myCell.Address
            Else
                MsgString = myCell.Address
            End If
        End If
    Next myCell

    MsgBox "The following cells are not equal to 0 :" & vbCr & MsgString, vbOKOnly

End Sub

注意Empty的单元格未输入<>0的条件,因此如果您还想查找空单元格,则代码需要一些修改