11

In Excel VBA is there a way to safely use Range("A1:B2").ClearContent without deleting the existent formulas in the cells?

Just to make my scenario clearer: I'm pulling fresh data from the database and just want to erase everything on the sheet but not the formulas because those will resolve some data in other fields with vlookups.

Community
  • 1
  • 1
Lorenzo
  • 4,558
  • 11
  • 44
  • 54

1 Answers1

17

Use the SpecialCells property to get only the constant values.

Sub RemoveConstants()

    Dim rConstants As Range

    Set rConstants = Sheet1.Range("A1:B2").SpecialCells(xlCellTypeConstants)
    rConstants.ClearContents

End Sub
Dick Kusleika
  • 32,673
  • 4
  • 52
  • 73
  • 2
    Note that if no cells in the range actually have values, Excel throws an error "No cells were found" in response to Set rConstants = Sheet1.Range("A1:B2").SpecialCells(xlCellTypeConstants) – Murrah Aug 05 '14 at 23:02
  • 3
    Add a `On Error Resume Next` at the start of the sub to avoid the "No cells were found" error. – Nikhil Gupta Jul 24 '15 at 10:24