Forum Discussion

ACPNR's avatar
ACPNR
Copper Contributor
May 02, 2019
Solved

Help - Cancel MsgBox If Condition is Met

Hello,   I'm trying to write a macro that does one thing or the other. There are two ranges: Code (H15:I32) and Repair_Comments (N15:R32). First, if X is marked in Code range then a message box sho...
  • IngeborgHawighorst's avatar
    May 02, 2019

    Hello ACPNR ,

     

    I think all you need to do is add another condition to the IF statement so it says in words "If the Code is X and the cell next to it is blank" then show the message.

     

    You only need to loop through the codes in column H,  and you don't need the $ signs in the range reference.  Also, when you dim several elements in one row of code, you need to specify the data type of each. If you don't, it will be a variant. 

     

    Also, you don't want to loop through the whole list. You only want to check the row where the data was entered, i.e. the target cell in column H. Therefore, the code should only watch column H, not column I.  When you operate on the target cell, you don't need to declare any ranges at all. 

     

    Private Sub Worksheet_Change(ByVal Target As Range)
        If Not Intersect(Target, Range("H15:H32")) Is Nothing Then
            If Target.Value = "X" And Len(Target.Offset(0, 1)) = 0 Then
                    MsgBox ("Please include a repair comment for corresponding line.")
            End If
        End If
    
    End Sub
    

    If you want to cater for a scenario where several rows of values are filled in at once, for example with a copy / paste operation, THEN you would need to loop through all the cells in the target. In that case it would also help to give the user an indication which row needs to be addressed.

     

    Private Sub Worksheet_Change(ByVal Target As Range)
    Dim cel As Range
        If Not Intersect(Target, Range("H15:H32")) Is Nothing Then
            For Each cel In Target
                If cel.Value = "X" And Len(cel.Offset(0, 1)) = 0 Then
                        MsgBox ("Please include a repair comment for row " & cel.Row & ".")
                End If
            Next cel
        End If
    
    End Sub