简体   繁体   中英

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

You will need to be sure the SelectData form is open. Do you have the code behind for the OK or Close button? If you use something like Me.Close then you won't have an object. You can, instead, use Me.Hide .

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

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