VBA Code to clear contents of a cell automatically when a trigger value is detected.

Postmaster383

New member
Joined
Jul 7, 2021
Messages
9
Reaction score
0
Points
0
Excel Version(s)
2013
[FONT=&quot]Hi all. I was hoping I could get some help with VBA code.[/FONT]
[FONT=&quot]I would like one particular cell (I5) to have contents cleared with one of either of the following two trigger words selected in another column (M4:M53). The trigger words are "NOON in PORT" or "NOON in TRANS".
[/FONT]

[FONT=&quot]Also, to make things clear, the trigger words have to be the last value in the mentioned column range. For example, if M25 has "NOON in PORT" selected it will clear I5. The spreadsheet is being copied new, renamed with present date and being updated on a daily basis. So if the next day M26 has "NOON at SEA" I5 will not be cleared and ignore [/FONT][FONT=&quot]"NOON in PORT" from the day before, [/FONT][FONT=&quot]and so on. Thanks for any help.[/FONT]
 
Here is a VBA solution for you

Code:
Option Explicit
Option Compare Text




Sub Noon()
    Dim lr As Long
    Dim i As Long
    lr = Range("M" & Rows.Count).End(xlUp).Row
    For i = lr To 4 Step -1
        If Range("M" & i) = "NOON in PORT" Or Range("M" & i) = "NOON in TRANS" Then
            Range("I5").ClearContents
            Exit Sub
        End If
    Next i
End Sub

Standard Module
How to install your new code
Copy the Excel VBA code
Select the workbook in which you want to store the Excel VBA code
Press Alt+F11 to open the Visual Basic Editor
Choose Insert > Module
Edit > Paste the macro into the module that appeared
Close the VBEditor
Save your workbook (Excel 2007+ select a macro-enabled file format, like *.xlsm)


To run the Excel VBA code:
Press Alt-F8 to open the macro list
Select a macro in the list
Click the Run button
 
Thanks for the reply. Much appreciated.

I was able to get this to work to automatically trigger when either "Noon in Port" or "Noon in Trans" was detected in the range. Also, as the spreadsheet was being copied, renamed and updated on a daily basis, it had to ignore previous "NOON in PORT" triggers so was looking only at the last value in the range.

I added a couple of other cells to clear contents, this is the code

Code:
Private Sub Worksheet_Change(ByVal target As Range)

Dim triggercells As Range, lrow As Integer


Set triggercells = Range("M4:M53")


If Not Application.Intersect(triggercells, Range(target.Address)) Is Nothing Then
    lrow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "M").End(xlUp).Row
    If Cells(lrow, 13).Value = "NOON in PORT" Then
        Range("I5,E4:F4,E5:F5").Select
    Range("E5").Activate
    Selection.ClearContents
    End If


    If Cells(lrow, 13).Value = "NOON in TRANS" Then
        Range("I5,E4:F4,E5:F5").Select
    Range("E5").Activate
    Selection.ClearContents
    End If
    
 Range("j13").Select
End If


End Sub

Thanks again
 
Back
Top