我有一系列工作表名称。我想从另一个文件中复制数据并将数据粘贴到相应的工作表中。但它找不到表格。它在此步骤中产生错误:
worksheets.(sheets(i)).Activate
这是我的代码:
Sub NewWorkshet()
Dim criteria(40) As Integer
Dim i As Integer
Dim MyFile As String
MyFile = Application.GetOpenFilename()
criteria(0) = 335
criteria(1) = 336
criteria(2) = 337
criteria(3) = 338
criteria(4) = 339
criteria(5) = 351
criteria(6) = 392
criteria(7) = 393
Dim sheets As Variant
sheets = Array(a335, a336, a337, a338, a339, a351, a392, a393)
For i = 0 To 7
' Remove Filter
Windows("firstbook.xlsx").Activate
ActiveSheet.Range("$A$1:$S$6274").AutoFilter Field:=17
Workbooks.Open (MyFile)
Worksheets("first").Select
ActiveSheet.Range("$A$1:$O$3339").AutoFilter Field:=2, Criteria1:=criteria(i)
Range("A2").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Windows("firstbook").Activate
Worksheets("sheets(i)").Select
Range("B2").Select
Selection.End(xlDown).Select
Selection.Offset(1, -1).Select
ActiveSheet.Paste
Workbooks(MyFile).Close SaveChanges:=False
Next i
End Sub
答案 0 :(得分:0)
它处理工作表(“sheet(i)”)。字面上选择 sheet(i)而不是变量。所以它不会改变,也不会找到你的表。
您需要为此创建一个字符串。
尝试添加Dim MySheet As String
然后在循环中使用它:
MySheet = "sheets(" & i & ")"
然后可以引用MySheet并根据需要进行更改。
答案 1 :(得分:0)
问题在于
Worksheets("sheets(i)").Select
正在寻找名为“sheet(i)”的工作表作为文本/名称 如果你改用
Worksheets(sheets(i)).Select
然后它正在寻找一个名为变量/数组sheets(i)
答案 2 :(得分:0)
您的问题是您没有将“工作表”值设置为文字。
sheets = Array(a335, a336, a337, a338, a339, a351, a392, a393)
代码应该是
Dim sheets(0 To 7) As Variant
sheets(0) = "a335"
sheets(1) = "a336"
sheets(2) = "a337"
sheets(3) = "a338"
sheets(4) = "a339"
sheets(5) = "a351"
sheets(6) = "a392"
sheets(7) = "a393"
然后参考如下;
Worksheets(sheets(i)).Select