There is a condition that most of these decisions are not considered. I reviewed Patrick Honorez's decision to handle this. I felt I had to share this because I was tearing my hair out when the original function sometimes deleted more data that I expected.
The situation occurs when the table has only one column and .SpecialCells(xlCellTypeConstants).ClearContents
tries to clear the contents of the top row. In this situation, only one cell is selected (the top row of the table, in which there is only one column), and the SpecialCells command is applied to the entire sheet, and not to the selected range. What happened to me was that other cells on the sheet that were outside of my desk were also cleared.
I rummaged around a bit and found this tip from Mathieu Gindon: Range SpecialCells ClearContents clears the entire sheet
Range ({any single cell}). SpecialCells ({whatever}) seems to work on the whole sheet.
Range ({more than one cell}). SpecialCells ({whatever}) seems to work from the specified cells.
If the list / table has only one column (in row 1), this edition will check if the cell has a formula, and if not, it will clear only the contents of this single cell.
Public Sub ClearList(lst As ListObject) 'Clears a listObject while leaving 1 empty row + formula ' https://stackoverflow.com/a/53856079/1898524 ' 'With special help from this post to handle a single column table. ' Range({any single cell}).SpecialCells({whatever}) seems to work off the entire sheet. ' Range({more than one cell}).SpecialCells({whatever}) seems to work off the specified cells. ' https://stackoverflow.com/questions/40537537/range-specialcells-clearcontents-clears-whole-sheet-instead On Error Resume Next With lst '.Range.Worksheet.Activate ' Enable this if you are debugging If .ShowAutoFilter Then .AutoFilter.ShowAllData If .DataBodyRange.Rows.Count = 1 Then Exit Sub ' Table is already clear .DataBodyRange.Offset(1).Rows.Clear If .DataBodyRange.Columns.Count > 1 Then ' Check to see if SpecialCells is going to evaluate just one cell. .DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents ElseIf Not .Range.HasFormula Then ' Only one cell in range and it does not contain a formula. .DataBodyRange.Rows(1).ClearContents End If .Resize .Range.Rows("1:2") .HeaderRowRange.Offset(1).Select ' Reset used range on the sheet Dim X X = .Range.Worksheet.UsedRange.Rows.Count 'see J-Walkenbach tip 73 End With End Sub
The last step I included is the advice that is attributed to John Walkenbach, sometimes referred to as the J-Walkenbach tip 73
Automatic J-Walkenbach tip 73
last cell
source share