0
votes

I need to cycle through the first 3 sheets of an Excel workbook and execute some code when it gets opened.

This is my code:

    Private Sub Workbook_Open()

Dim I As Integer

For I = 1 To 3
  Sheets(I).Select
  sam_crm = Range("I2").Value
  ActiveSheet.ListObjects(1).Range.AutoFilter Field:=1, Criteria1:=sam_crm
  ActiveSheet.ListObjects(2).Range.AutoFilter Field:=5, Criteria1:=sam_crm
  ActiveSheet.ListObjects(2).Range.AutoFilter Field:=1, Criteria1:="<>*" & sam_crm & "*", Operator:=xlAnd
Next I   
Sheets(1).Select 
End Sub

I get

error 1004, select method of the worksheet object could not be executed

I'm using the German version of excel, so I don't know the exact English error message. It is working fine with Excel 2007, but since the last update it isn't working on the newer versions.

1
Substitute .Select for .Activate, I would make an answer, but thing is too short to be one. - AntiDrondert
I also tried .Activate. The error message changes to "error 1004, activate method of the worksheet object could not be executed" - Dirk Sachse
What would the purpose of this code be? Why not just activate sheet(1). - Davesexcel
What about ThisWorkbook.Worksheets(I).Activate ? - AntiDrondert
Avoid .Select and .Activate at all that's a bad practice use Sheets(I).ListObjects(1)… directly. Also specify a sheet for your ranges Sheets(I).Range("I2").Value - Pᴇʜ

1 Answers

0
votes
  1. Use Option Explicit to force proper variable declare
  2. Try to avoid .Select and .Activate and ActiveSheet. instead specify a worksheet by its name.

Here is an improvement of your code

Option Explicit 'forces variable declare 

Private Sub Workbook_Open()
    Dim i As Long 'use long instead of integer, there is no advantage in integer
    For i = 1 To 3
        Dim sam_crm As Variant
        With Sheets(i) 
            sam_crm = .Range("I2").Value 'due to the WITH statement above this is the same
                                         'like sam_crm = Sheets(i).Range("I2").Value
                                         'but just shorter
                                         'and the same also for .ListObjects below …
            .ListObjects(1).Range.AutoFilter Field:=1, Criteria1:=sam_crm
            .ListObjects(2).Range.AutoFilter Field:=5, Criteria1:=sam_crm
            .ListObjects(2).Range.AutoFilter Field:=1, Criteria1:="<>*" & sam_crm & "*", Operator:=xlAnd
        End With
    Next i   

    'it might be that the workbook is not fully loaded at this point so
    'ThisWorkbook.Sheets(1).Select might fail. So we can try to wait until the
    'Application is ready:
    Do: DoEvents: Loop While Not Application.Ready 'runs a loop until Application.Ready = True

    ThisWorkbook.Sheets(1).Select 'or .Activate is OK here because we really want to 
                                  'select it so this is what the user sees.
End Sub