AutoFilterMode的优化

时间:2016-12-07 07:49:13

标签: excel-vba autofilter vba excel

我已经写了这篇VBA,它完全符合我的要求。然而,大多数值重复自己很多时间,我想知道下面是否可以转换成循环。当然这可以通过某种方式进行优化,但我很难看到,特别是如果“AutoFilter”只能携带一个“Field”。有什么想法吗?

OutputStream outStream = socket.getOutputStream();
byte[] bytes = <some-data>
outStream.write(bytes);

1 个答案:

答案 0 :(得分:2)

使用Excel.WorksheetFunction.CountIfs而不是AutoFilter只是用于计算具有某些条件的行数会更快。你可以替换它:

    .AutoFilterMode = False
    .Range("A:E").AutoFilter Field:=1, Criteria1:="=*apple"
    .Range("A:E").AutoFilter Field:=14, Criteria1:="america"
    j = .AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Cells.Count - 1
    Sheets(15).Cells(18, 2) = j

有了这个:

Sheets(15).Cells(18, 2) = Excel.WorksheetFunction.CountIfs(Sheets(7).Columns(1), "=*apple", Sheets(7).Columns(14), "america")

因此,您可以通过以下方式轻松替换代码:

With Sheets(7)
    Sheets(15).Cells(18, 2) = Excel.WorksheetFunction.CountIfs(.Columns(1), "=*apple", .Columns(14), "america")
    Sheets(15).Cells(19, 2) = Excel.WorksheetFunction.CountIfs(.Columns(1), "=*apple", .Columns(14), "asia")
    Sheets(15).Cells(20, 2) = Excel.WorksheetFunction.CountIfs(.Columns(1), "=*apple", .Columns(14), "europe")
    Sheets(15).Cells(21, 2) = Excel.WorksheetFunction.CountIfs(.Columns(1), "=*apple", .Columns(14), "africa")
    Sheets(15).Cells(18, 3) = Excel.WorksheetFunction.CountIfs(.Columns(1), "=*apple", .Columns(15), "america", .Columns(12), "red")
    Sheets(15).Cells(19, 3) = Excel.WorksheetFunction.CountIfs(.Columns(1), "=*apple", .Columns(15), "asia", .Columns(12), "green")
    Sheets(15).Cells(20, 3) = Excel.WorksheetFunction.CountIfs(.Columns(1), "=*apple", .Columns(15), "europe", .Columns(12), "yellow")
    Sheets(15).Cells(21, 3) = Excel.WorksheetFunction.CountIfs(.Columns(1), "=*apple", .Columns(15), "africa", .Columns(12), "dark red")
    Sheets(15).Cells(18, 5) = Excel.WorksheetFunction.CountIfs(.Columns(1), "=*apple", .Columns(17), "america")
    Sheets(15).Cells(19, 5) = Excel.WorksheetFunction.CountIfs(.Columns(1), "=*apple", .Columns(17), "asia")
    Sheets(15).Cells(20, 5) = Excel.WorksheetFunction.CountIfs(.Columns(1), "=*apple", .Columns(17), "europe")
    Sheets(15).Cells(21, 5) = Excel.WorksheetFunction.CountIfs(.Columns(1), "=*apple", .Columns(17), "africa")
End With

在这一点上很好,因为创建一个循环会很棘手,因为你的条件是不规则的。但是,您可以像这样包装它:

cols = Array(2, 3, 5)
contin = Array("america", "asia", "europe", "africa")
colour = Array("red", "green", "yellow", "dark red")

For Each k In cols
    For i = 0 To 3
        If k <> 3 Then Sheets(15).Cells(i + 18, k) = Excel.WorksheetFunction.CountIfs(Sheets(7).Columns(1), "=*apple", Sheets(7).Columns(12 + k), contin(i))
        If k = 3 Then Sheets(15).Cells(i + 18, k) = Excel.WorksheetFunction.CountIfs(Sheets(7).Columns(1), "=*apple", Sheets(7).Columns(12 + k), contin(i), Sheets(7).Columns(12), colour(i))
    Next i
Next k