excelvba

Clear certain cells with X style


I select a sheet and ClearContents anything that has a particular style.

The code is crashing.

Expected to delete anything in a given style.

Sub Reset_User_Inputs()

    Dim input_cell As Range
    
    Sheet1.Activate
    
    Sheet1.Cells.Select
    
    For Each input_cell In Selection
        If input_cell.Style = "RESETABLE" Then
            input_cell.ClearContents
        End If
    Next input_cell
    
End Sub

Solution

  • Clear Cells With a Certain Style

    Sub ResetUserInputs()
        
        ' Combine the critical cells into a range.
         
        Dim urg As Range, cell As Range
    
        With Sheet1.UsedRange
        
            For Each cell In .Cells
                If cell.Style = "RESETABLE" Then
                    If urg Is Nothing Then
                        Set urg = cell
                    Else
                        Set urg = Union(urg, cell)
                    End If
                End If
            Next cell
        
        End With
    
        ' Clear the range in one go.
        
        If Not urg Is Nothing Then
            urg.ClearContents
        End If
    
        ' Inform.
    
        MsgBox "User inputs reset.", vbInformation
    
    End Sub