VBA自动过滤基于数组的动态日期

时间:2018-06-21 11:58:13

标签: vba

我一直在尝试创建子对象,该子对象创建日期数组以基于动态数组应用自动过滤器,但是在应用过滤器时出错。

  

“范围类的自动筛选方法失败”

如果我应用手动创建的数组,则会被罚款

Private Sub CreateDateArayy()
Dim myArray() As Variant
Dim PreRng, PostEng As Range
Dim src, tgt As Worksheet
Set tgt = Worksheets("Main")
Dim CellCount, x As Integer
CellCount = 0: x = 0:
Set PreRng = tgt.Range("C2:C16")

For Each cell In PreRng
    If cell.Value <> "" Then
    CellCount = CellCount + 1
    End If
Next cell

ReDim myArray(CellCount * 2)

For Each cell In PreRng
    If cell.Value <> "" Then
    myArray(x) = 2
    myArray(x + 1) = cell.Value
    x = x + 2
    End If
Next cell

d = testfilter(myArray)

End Sub

Function testfilter(dates As Variant)

Dim sht As Worksheet
Set sht = Worksheets("Daily Data")
sht.AutoFilterMode = False
sht.UsedRange.AutoFIlter Field:=2, Operator:=xlFilterValues, Criteria2:=dates

End Function

1 个答案:

答案 0 :(得分:0)

通过更改行来解决

ReDim myArray(CellCount * 2)

ReDim myArray(CellCount * 2 - 1)