【发布时间】:2021-09-12 21:05:21
【问题描述】:
我正在尝试修改此页面中的脚本:https://www.listendata.com/2015/04/excel-vba-filtering-and-copy-pasting-to.html,综合起来,我可以过滤列中的每个唯一值、复制数据、创建新工作簿,然后将所述数据粘贴到循环中。
问题是每次脚本继续创建新工作簿并粘贴复制的数据时,我都会收到错误 Run-time Error 9: Subscript out of range 正好在下面加粗的行中:
Sub test()
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
' -------------------
Dim x As Range
Dim rng As Range
Dim rng1 As Range
Dim last As Long
Dim sht As String
Dim newBook As Excel.Workbook
Dim Workbk As Excel.Workbook
'Specify sheet name in which the data is stored
sht = "Report"
'Workbook where VBA code resides
Set Workbk = ThisWorkbook
'New Workbook
Set newBook = Workbooks.Add(xlWBATWorksheet)
Workbk.Activate
'change filter column in the following code
last = Workbk.Sheets(sht).Cells(Rows.Count, "BR").End(xlUp).Row
With Workbk.Sheets(sht)
Set rng = .Range("A1:BR" & last)
End With
Workbk.Sheets(sht).Range("G1:G" & last).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("BT1"), Unique:=True
For Each x In Workbk.Sheets(sht).Range([BT2], Cells(Rows.Count, "BT").End(xlUp))
With rng
.AutoFilter
.AutoFilter Field:=7, Criteria1:=x.Value
.SpecialCells(xlCellTypeVisible).Copy
*newBook.Sheets.Add(After:=Sheets(Sheets.Count)).Name = x.Value*
newBook.Activate
ActiveSheet.Paste
End With
Next x
' Turn off filter
Workbk.Sheets(sht).AutoFilterMode = False
With Application
.CutCopyMode = False
.ScreenUpdating = True
End With
' -------------------
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
MsgBox "Check."
End Sub
值得一提的是,新工作簿已创建。但是它卡在这里,我看不出原因。
【问题讨论】:
标签: vba loops filter filtering