1004选择方法错误

时间:2018-02-16 12:10:02

标签: excel vba excel-vba

我需要遍历Excel工作簿的前3页,并在打开时执行一些代码。

这是我的代码:

    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

我得到了

  

错误1004,无法选择工作表对象的方法   执行

我使用德语版的excel,所以我不知道确切的英文错误消息。它在Excel 2007中运行良好,但自上次更新以来,它不适用于较新版本。

1 个答案:

答案 0 :(得分:0)

  1. 使用Option Explicit强制执行适当的变量声明
  2. 尽量避免使用.Select.Activate以及ActiveSheet.来指定工作表的名称。
  3. 以下是对代码的改进

    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