Home » excel » excel – Select Case Error: Object variable of With block variable not set

excel – Select Case Error: Object variable of With block variable not set

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to write a little macro that on click hides specific columns and on the second click shows them again.

My macro already worked with colors as a premise but my boss told me he needs it with the specific names in the Case Query.

My old macro which worked (just for your information)

Option Explicit
Public s As Integer
Sub hideColumns()
   Dim c As Range
    If s = 0 Then
    For Each c In ActiveSheet.UsedRange.Rows(4).Cells
        If c.Interior.ColorIndex = xlNone Then
        c.EntireColumn.Hidden = True
        End If
    Next c
    s = 1
    ElseIf s = 1 Then
        For Each c In ActiveSheet.UsedRange.Rows(4).Cells
        If c.Value <> "" Then
        c.EntireColumn.Hidden = False
        End If
    Next c
    s = 0
    End If
End Sub

And my new macro with string comparison which doesn’t work.

Option Explicit
Public s As Integer
Sub hideColumns()
   Dim c As Range
    If s = 0 Then
    Select Case c.Value
    Case "SNR-A", "SNRBEZ-A", "DEPTCO-A", "NW-A", "WPKURS-A", "KW-A", "KUBER1-A", "AKS-TEAMGR"
        c.EntireColumn.Hidden = False
    Case Else
        c.EntireColumn.Hidden = True
    End Select
    s = 1
    ElseIf s = 1 Then
        For Each c In ActiveSheet.UsedRange.Rows(4).Cells
        If c.Value <> "" Then
        c.EntireColumn.Hidden = False
        End If
    Next c
    s = 0
    End If
End Sub

I always get the error “Object variable or With block variable not set” and I cant figure out why.

How to&Answers:

You’re getting “object variable not set” because you’re making a member call against an object variable whose reference is not set. In the first snippet, c is assigned by the For Each iterator, so member calls against c are legal inside the loop body:

   Dim c As Range
    If s = 0 Then
    For Each c In ActiveSheet.UsedRange.Rows(4).Cells
        If c.Interior.ColorIndex = xlNone Then
        c.EntireColumn.Hidden = True
        End If
    Next c

In the second/errorring snippet, the members of c are accessed before c is assigned to anything:

   Dim c As Range
    If s = 0 Then
    Select Case c.Value

That will raise run-time error 91 every single time. You need to Set c = SomeRangeOnSomeSheet before you can access c.Value. Without a Set assignment, the value of c is Nothing.