[英]subscript out of range VBA Excel, advanced filter macro
I'm stuck on the last bit of this Excel macro. 我被困在这个Excel宏的最后一位。 I adapted it from this template to do advanced filtering on a list of data based on criteria the user enters. 我从此模板对其进行了修改,以便根据用户输入的条件对数据列表进行高级过滤。
I get a subscript out of range error on line Sheets("Data (2)").ListObjects("table4").TableStyle = "TableStyleMedium2"
我在Sheets("Data (2)").ListObjects("table4").TableStyle = "TableStyleMedium2"
上出现下标超出范围错误
table4
where all my data is hanging out; table4
我所有的数据都挂在哪里; I named this by selecting the relevant cells and then naming that range. 我通过选择相关的单元格然后命名该范围来命名它。
added the Dim table4 As String
line above; 在上面添加了Dim table4 As String
行; it was not in the original code but when I looked up the error in Excel help it said I need to declare the array first. 它不在原始代码中,但是当我在Excel帮助中查找错误时,它说我需要首先声明该数组。 Data are just text strings so string
is fine - I won't be calculating anything after the filter is complete. 数据只是文本字符串,所以string
很好-过滤器完成后,我将不进行任何计算。
Any ideas? 有任何想法吗?
Option Explicit
Private Sub btnFilter_Click()
Application.ScreenUpdating = False
' clear old data first
Dim n As Long
n = Cells(Rows.Count, "A").End(xlUp).Row
If n > 23 Then
Rows("24:" & CStr(n)).Delete Shift:=xlUp
End If
With Sheets("Data (2)")
.Select
' apply filter
.Range("A:AW").AdvancedFilter Action:=xlFilterInPlace, CriteriaRange:=.Range("Criteria2"), Unique:=False
' select filtered rows
Dim rngFilter As Range
Set rngFilter = .Range("A2", .Cells(.Rows.Count, "A").End(xlUp)).Resize(, 9)
' count number of filtered rows
On Error Resume Next
n = 0
n = rngFilter.SpecialCells(xlCellTypeVisible).Rows.Count
On Error GoTo 0
If n = 0 Then
Sheets("Filter (2)").Select
' skip copying
GoTo skip_copying
End If
' copy selection
rngFilter.Select
Selection.Copy
End With
' paste new data
Sheets("Filter (2)").Select
Sheets("Filter (2)").Range("A24").Select
ActiveSheet.Paste
Application.CutCopyMode = False
Sheets("Filter (2)").Range("A24").Select
skip_copying:
' remove filter
Sheets("Data (2)").ShowAllData
' table style
Dim table4 As String
Sheets("Data (2)").ListObjects("table4").TableStyle = "TableStyleMedium2"
Application.ScreenUpdating = True
End Sub
You created a named range, not a ListObject
, so your reference to table4
is unrecognized. 您创建的是命名范围,而不是ListObject
,因此无法识别对table4
的引用。 Here are instructions for making your data range into a ListObject
: https://msdn.microsoft.com/en-us/library/eyfs6478.aspx 以下是将数据范围设置为ListObject
: https : //msdn.microsoft.com/zh-cn/library/eyfs6478.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.