Search code examples
vbaexcelexcel-2013

Object required error in Workbook_Open with For loop


***It's working!! Thanks everyone for the help :D - turns out range was declared and set as "columnnrange" and the for loop was using "columnrange". It's the little things ;) . Appreciate the insight and guidance all!

*Thanks for the help everyone! I've updated the code per the responses. The error definitely comes when the For loop runs - if it is commented out there is no error. I believe the error is with the range "columnrange" object. Thanks!!

I have a simple Workbook_Open() routine that opens a UserForm "SelectData" and sets a ComboBox "DisplayData" value. I have a MsgBox that confirms the value set in the ComboBox "DisplayData".
Once set, the UserForm "SelectData" is hidden. Then, there is a "for" loop to hide all columns where the given cell in range "columnrange" is not equal to the ComboBox value. I'm getting an error "object required" but for the life of me cannot figure out where I'm going wrong. The goal of this spreadsheet is: "on open", allow the user to filter the visible columns on an excel doc exported from a SharePoint list.
Thanks in advance!!

Private Sub Workbook_Open()

Dim columnrange As Range
Dim cell As Range

Set columnnrange = ActiveWorkbook.Worksheets("owssvr").Range("G1:Z1")

SelectData.Show

MsgBox (SelectData.DisplayData.Value)

For Each cell In columnrange
    If SelectData.DisplayData.Value <> cell Then
        cell.EntireColumn.Hidden = True
   Else
        cell.EntireColumn.Hidden = False
   End If
Next cell


End Sub

Solution

  • Change the loop condition to verify cell instead of columnrange. Here is a simplified code that should work.

    For Each cell In columnrange    
        If SelectData.DisplayData.Value <> cell Then
            cell.EntireColumn.Hidden = True
        Else
            cell.EntireColumn.Hidden = False
        End If    
    Next cell