excelvbatype-mismatch

Type Mismatch Using ActiveSheet.UsedRange


Code below is supposed to hide all columns where any of its cells contain a certain value. If I directly specify a search Range, it works. However, if I use "ActiveSheet.UsedRange", it throws a type mismatch error. What is going on?

Sub HideColumn()

    Dim MySel As Range
    
    For Each cell In ActiveSheet.UsedRange
        If cell.Value = "X123" Then
            If MySel Is Nothing Then
                Set MySel = cell
            Else
                Set MySel = Union(MySel, cell)
            End If
        End If
    Next cell
    
    MySel.EntireColumn.Hidden = True
End Sub

Solution

  • Hide Columns of Cells Equal To a String

    Option Explicit
    
    Sub HideColumns()
    
        If ActiveSheet Is Nothing Then Exit Sub ' no visible workbooks open
        If Not TypeOf ActiveSheet Is Worksheet Then Exit Sub ' not a worksheet
    
        Dim rg As Range: Set rg = ActiveSheet.UsedRange
    
        Dim crg As Range, cell As Range, urg As Range
        
        For Each crg In rg.Columns
            For Each cell In crg.Cells
                If StrComp(CStr(cell.Value), "X123", vbTextCompare) = 0 Then
                    If urg Is Nothing Then
                        Set urg = cell
                    Else
                        Set urg = Union(urg, cell)
                    End If
                    Exit For ' match in column found; no need to loop anymore
                End If
            Next cell
        Next crg
        
        rg.EntireColumn.Hidden = False ' unhide all columns
        If Not urg Is Nothing Then urg.EntireColumn.Hidden = True ' hide matching
    
    End Sub