'Clear column content in Excel table based on specific cell value

I have the following Table in my macro-enabled excel file,

Table1:

enter image description here

My goal is:

Before closing this workbook, I need to clear Column D content (shown as "Column 4" in the Table1), only where column D cells value = 999. For example, looking at the screenshot above - cell content in D2 and in D4 must be cleared when "close workbook" event triggered.

Important - if user will create a new record(s) in this table, then any new cell under Column D could have 999 value too. If a new record contains cell value = 999 in the Column D - it must be cleared! Any new record where cell value = 999 in column D must be cleared!

See updated picture of what I expect -

cells D2, D4, and also D7 (after the new record created in this tbl) had 999 value and cleared:

enter image description here

Using the following vba code but it's not working:

     Private Sub Workbook_BeforeClose(Cancel As Boolean)

        Dim sht As Worksheet
        Set sht = ThisWorkbook.ActiveSheet

        If Worksheets("Sheet1").ListObjects("Table1").Columns(4).Value = 999 Then
           Worksheets("Sheet1").ListObjects("Table1").Columns(4).ClearContents
  
        End If

    End Sub


Solution 1:[1]

Clear Values in an Excel Table

Option Explicit

Private Sub Workbook_BeforeClose(Cancel As Boolean)

    Dim ws As Worksheet: Set ws = Me.Worksheets("Sheet1")
    Dim tbl As ListObject: Set tbl = ws.ListObjects("Table1")
    Dim lcl As ListColumn: Set lcl = tbl.ListColumns("Column 4") ' 4
        
    lcl.DataBodyRange.Replace 999, Empty, xlWhole
    
End Sub

EDIT

  • If you want to avoid the 'save alert dialog' when the workbook was already saved you can improve with the following:
Option Explicit

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    
    Dim IsSaved As Boolean: IsSaved = Me.Saved
    
    Dim ws As Worksheet: Set ws = Me.Worksheets("Sheet1")
    Dim tbl As ListObject: Set tbl = ws.ListObjects("Table1")
    Dim lcl As ListColumn: Set lcl = tbl.ListColumns("Column 4") ' 4
        
    lcl.DataBodyRange.Replace 999, Empty, xlWhole
    
    If IsSaved Then Me.Save
    
End Sub

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1