1

I have a table I would like to clear, getting object required error on my range line.

I also have tried other things but it tends to also clear the current page im on.

Sub ClearDatabase()
    With ThisWorkbook.Worksheets("database").Select
        Range("A2:FR" & .Cells(.Rows.count, "A").End(xlUp).row).ClearContents  'adjust this if needing to clear more
    End With
End Sub
excelguy
  • 1,574
  • 6
  • 33
  • 67
  • In addition to [Jeeped's answer](https://stackoverflow.com/a/52301742/2344413), learn how to [avoid using .Select](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba) – FreeMan Sep 12 '18 at 19:02

1 Answers1

2

Use the With ... End With block properly.

Sub ClearDatabase()
    With ThisWorkbook.Worksheets("database")
        'adjust this if needing to clear more
        .Range("A2:FR" & .Cells(.Rows.count, "A").End(xlUp).row).ClearContents  
        'alternate
        '.Range(.cells(2, "A"), .Cells(.Rows.count, "A").End(xlUp).offset(0, 173)).ClearContents
    End With
End Sub

The .CurrentRegion property will cover the area radiating out from A1 until it reaches a full blank row and fully blank column.

Sub ClearDatabase()
    With ThisWorkbook.Worksheets("database")
        'offset preserves the column header labels in row 1
        .Range("A1").CurrentRegion.offset(1, 0).ClearContents  
    End With
End Sub