简体   繁体   中英

ClearContents for constants but not formulas

I've got a range (N1:N12) on a sheet1 and I've got a code that copy and paste me the values of that range on a secondary sheet2. Everything is working, anyway i didn't consider that i want another button that clear only values in range N1:N12 once i have copied them in sheet2. I don't know how to keep formulas on that range when i want to delete values. Do you have an idea ? I've already tried a normal macro that deletes everything but it is not what i want.

Sub Cancella() 
    Sheets("Foglio1").select 
    Range("N1:N12").clearcontents
End Sub

The code i use for copying

Dim lastRow As Long
    Sheets("Training Analysis").Range("P1:R13").Copy

    lastRow = Sheets("Foglio1").Range("a65536").End(xlUp).Row

    Sheets("Foglio1").Range("A" & lastRow + 1).PasteSpecial Paste:=xlPasteValues, Transpose:=True

Replace:

Range("N1:N12").clearcontents

with:

For i = 1 To 12
   If Not Cells(i, "N").HasFormula Then Cells(i, "N").ClearContents
Next i

There is a subset of the Range.SpecialCells method that targets xlCellTypeConstants . This can be further broken down to xlNumbers, xlTextValues, xlErrors , xlLogical or a combination of same.

With WorkSheets("Foglio1")
    .Range("N1:N12").SpecialCells(xlCellTypeConstants, xlNumbers).ClearContents
End With

Conversely, cells containing formulas can be similarly targeted with the xlCellTypeFormulas subset.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM