自动过滤器无法正常工作

时间:2009-11-06 21:47:04

标签: excel-vba vba excel

我有一个13行的范围,第一行是标题行,接下来的12行是由QueryTable填充的。查询最多返回12行,但可能更少。在这个范围之下,我有一个总行。

我想隐藏任何没有数据的行,而我正在使用AutoFilter来执行此操作。当我运行代码时,它会创建AutoFilter但不会应用条件。如果我单步执行代码,它就可以正常工作。有什么想法吗?

Sub fillTable()
    Dim strConn As String
    Dim strSQL As String
    Dim qt As QueryTable

    Sheet15.AutoFilterMode = False

    Sheet15.Range("DCRTable").ClearContents
    strConn = "ODBC;DSN=MS Access Database;DBQ=<db path>;"
    Set qt = Sheet15.QueryTables.Add(strConn, Sheet15.Range("DCRTable"))
    qt.CommandText = <sql query>
    qt.AdjustColumnWidth = False
    qt.EnableRefresh = False
    qt.FieldNames = False
    qt.Refresh

    hideEmpties Sheet15.Range("DCRTable").offset(-1).Resize(13)
End Sub

Sub hideEmpties(rng As Range)
    rng.Parent.AutoFilterMode = False
    With rng
        .AutoFilter
        .AutoFilter 1, "<>", , , False
    End With
End Sub

1 个答案:

答案 0 :(得分:1)

首先,我无法看到你如何将工作表分配给对象“Sheet15” - 这可能是问题的一部分。如果您有一个命名范围,则在此之前不需要Sheet对象。

其次,.Autofilter没有任何参数只是打开/关闭自动过滤器箭头,你就失去了标准。

试试这段代码吧,它对我有用(Office 2003)......我在A1中有一个标题,后面是A2..A13,名为DRCTable,后面是A14中的= SUM(DRCTable)

编辑2010年1月2日

(抱歉,我无法从我的假期住所测试ODBC,所以这部分只在语法上进行测试)

Sub fillTable()
Dim MySheet As Worksheet, MyRange As Range
Dim MyQRY As QueryTable, MyCONNECT As String, MySELECT As String ' added 02-Jan-2010

    'initialize
    Set MySheet = Sheets("Sheet1")
    Set MyRange = Range("DRCTable")

    MyCONNECT = "ODBC;..."           ' added 02-Jan-2010
    MySELECT = "SELECT * FROM DUAL"  ' added 02-Jan-2010 .. noticed my Oracle past :) ??

    Set MyQRY = ActiveSheet.QueryTables.Add(Connection:=MyCONNECT, _
                                            Destination:=MyRange, _
                                            Sql:=MySELECT)

    ' clean up
    MySheet.AutoFilterMode = False
    MyRange.ClearContents

    ' simulate Query      removed 02-Jan-2010
    ' MyRange(1, 1) = 1   removed 02-Jan-2010
    ' MyRange(2, 1) = 2   removed 02-Jan-2010
    ' MyRange(3, 1) = 3   removed 02-Jan-2010
    ' MyRange(4, 1) = 4   removed 02-Jan-2010
    ' MyRange(5, 1) = 5   removed 02-Jan-2010

    ' added 02-Jan-2010
    ' BackgroundQuery = FALSE waits until query is executed
    '                 = TRUE continues with VBA once connection to DB is made

    MyQRY.BackgroundQuery = False ' set this to affect all subsequet refresh
                                  ' and don't use the bool in refresh except
                                  ' to override the setting

    MyQRY.Refresh False ' the false sets BackgroundQuery for the individual refresh;
                        ' there is no default on this param within the refresh method.
                        ' If unspecified here the QueryTable.BackgroundQuery property
                        ' is examined

    ' select data range plus header and filter
    Range(MyRange.Offset(-1, 0), MyRange(12, 1)).AutoFilter _
        Field:=1, Criteria1:="<>"

End Sub

希望有所帮助 祝你好运MikeD