MsgBox for a range of cells

二次信任 提交于 2020-01-04 09:23:04

问题


I'm trying to create a code that displays a MsgBox if contents in cells of column G are not equal to 0. Code works with just one cell but not with the full range (G20:G100). can you please help. thanks

Private Sub Worksheet_Calculate()

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

End Sub

回答1:


Try like this:

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

It checks every cell in the range. For the first cell it finds with a different value than 0, it gives a MsgBox with its address and it exits.

You can make the MsgBox a bit more informative, showing the current value of the cell like this:

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

If you remove the Exit Sub it will show different MsgBox-es for each cell that is different than 0.




回答2:


The code below is a little longer, but you will get the result in 1 summary MsgBox with a list of all cells in the Range("G20:G" &LastRow) which are <>0.

Code

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

Note: cell which are Empty do not enter the criteria of <>0, so if you want also to find empty cells as well, the code will need some slight modifications.



来源:https://stackoverflow.com/questions/49532778/msgbox-for-a-range-of-cells

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!