[英]1004 Select Method error
I need to cycle through the first 3 sheets of an Excel workbook and execute some code when it gets opened. 我需要浏览Excel工作簿的前三页,并在打开它时执行一些代码。
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 错误1004,无法执行工作表对象的选择方法
I'm using the German version of excel, so I don't know the exact English error message. 我使用的是德语版本的excel,所以我不知道确切的英语错误消息。 It is working fine with Excel 2007, but since the last update it isn't working on the newer versions. 它可以在Excel 2007上正常工作,但是自上次更新以来,它不适用于较新的版本。
Option Explicit
to force proper variable declare 使用Option Explicit
强制进行适当的变量声明 .Select
and .Activate
and ActiveSheet.
尝试避免.Select
和.Activate
和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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.