在VBA

时间:2017-05-16 14:41:51

标签: excel vba excel-vba

我正在尝试做一些奇怪的事情,这可能不是唯一的方法,而且可能是错误的。我想迭代可见单元格(这是VBA的AutoFilter函数的结果)。

这是我以前做过的,它有效,但不是我想要的:  Sheets("MySheet").Range("$A$3:$AI$10191").AutoFilter Field:=12, Criteria1:=myList, Operator:=xlFilterValues。 myList是一个String列表,如下所示:Dim myList() as String  目前,这不适合我想要的:我不希望这个采取空白单元格,我也希望myList()内容近似采取(类似“”& myList&““)。

为此,我尝试了一行简单的代码,它可以工作:  Sheets("MySheet").Range("$A$3:$AI$10191").AutoFilter Field:=12, Criteria1:="*"&myList(0)&"*", Operator:=xlFilterValues

我的问题是:我想对列表中的所有元素执行此操作。我一直在考虑迭代我的列表(myList),但每次我进行新的迭代时,它都不会采用前一次迭代的结果实际上,我只想过滤“已过滤”的行...... 我已经使用.SpecialCells(xlCellTypeVisible)尝试了这个方法,但它需要所有单元格,而不仅仅是可见的单元格....(这里是带有可见单元格的完整代码:Sheets("MySheet").Range("$A$3:$AI$10191").SpecialCells(xlCellTypeVisible).AutoFilter Field:=12, Criteria1:="*"&myList(0)&"*", Operator:=xlFilterValues

我一直在考虑这样的事情:

For i =0 to UBound(myList)
    Sheets("MySheet").Range("$A$3:$AI$10191").SpecialCells(xlCellTypeVisible).AutoFilter Field:=12, Criteria1:="*"&myList(i)&"*", Operator:=xlFilterValues
Next i

但它只是按照上一个.AutoFilter规则进行过滤。 (它在i=UBound(myList)上过滤,因为每个.AutoFilter正在删除前一个的工作......)

如果您有任何想法......谢谢,Clément。

1 个答案:

答案 0 :(得分:1)

要试用高级过滤器,您可以尝试一下。 根据需要调整它......

Sub AdvancedFilter()
Dim wsData As Worksheet, wsCriteria As Worksheet
Dim myList() As String
Dim i As Long, lr As Long
Dim Rng As Range, Cell As Range

Application.ScreenUpdating = False

Set wsData = Sheets("MySheet")
If wsData.FilterMode Then wsData.ShowAllData
lr = wsData.UsedRange.Rows.Count

On Error Resume Next
Set wsCriteria = Sheets("Criteria")
wsCriteria.Cells.Clear
On Error GoTo 0

If wsCriteria Is Nothing Then
    Sheets.Add.Name = "Criteria"
    Set wsCriteria = ActiveSheet
End If

'Assuming myList has already been populated

'Writing the column header (column 12) on Criteria Sheet in A1
wsCriteria.Cells(1, 1) = wsData.Cells(1, 12)

'Adding wild card to each element in myList
For i = 1 To UBound(myList)
    myList(i) = "*" & myList(i) & "*"
Next i

'Writing myList on Criteria Sheet
wsCriteria.Range("A2").Resize(UBound(myList)).Value = Application.Transpose(myList)

'Using Advanced Filter on Data Sheet with Criteria on Criteria Sheet
wsData.Range("A1").CurrentRegion.AdvancedFilter xlFilterInPlace, wsCriteria.Range("A1").CurrentRegion

'Deleting the Criteria Sheet as it is not required now
Application.DisplayAlerts = False
wsCriteria.Delete
Application.DisplayAlerts = True

'Setting Rng as visible cells in column A
On Error Resume Next
Set Rng = wsData.Range("A2:A" & lr).SpecialCells(xlCellTypeVisible)

If Not Rng Is Nothing Then
    For Each Cell In Rng
        'Do your stuff here with visible range
    Next Cell
End If
If wsData.FilterMode Then wsData.ShowAllData
Application.ScreenUpdating = True
End Sub