简体   繁体   中英

Range SpecialCells ClearContents clears whole sheet instead

I have a sheet in Excel 2010 which is setup as a pseudo form (I didn't create it, I'm just trying to fix it) so formatting suggests that the user can only enter in certain cells. Depending on certain functionality these areas need to be reset, ie cleared although formulae and standard/conditional formatting need to be kept. I have defined each of these cells/ranges as named ranges so I can easily loop through them using the following code: -

Public Sub ResetDetailSheet()
    Dim nm As Name

    With ThisWorkbook
        For Each nm In .Names
            If Left(nm.Name, 9) = "nmrDetail" Then
                Range(nm.Name).SpecialCells(xlCellTypeConstants).ClearContents
            End If
        Next
    End With
End Sub

For some reason instead of clearing the constants from the specific range it is clearing constants from the entire sheet so I am losing all titles/headings. Formulae and standard/conditional formatting are staying as expected.

What am I doing wrong?!?!

As a test using the immediate window I tried clearing a specific cell, eg

Range("G7").SpecialCells(xlCellTypeConstants).ClearContents

But this still cleared all constants from the entire sheet.

What am I missing? I don't understand. Maybe I'm being dumb. Sorry, I can't upload an example. This place is pretty locked down.

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.

So, make sure your range has more than a single cell before you clear it - if the range is only a single cell, then check if it .HasFormula ; if that's the case then its .Value isn't a constant:

With ThisWorkbook
    For Each nm In .Names
        If Left(nm.Name, 9) = "nmrDetail" Then
            If nm.RefersToRange.Count > 1 Then
                nm.RefersToRange.SpecialCells(xlCellTypeConstants).ClearContents
            ElseIf Not nm.RefersToRange.HasFormula Then
                nm.RefersToRange.ClearContents
            End If
        End If
    Next
End With

Note that I'm using Name.RefersToRange instead of fetching the range by name off the active sheet.

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