【发布时间】:2017-04-21 00:50:53
【问题描述】:
Manual choice使用我从互联网上修改的代码我已经正确过滤了我的表格日期,但是当单击按钮时,它不会显示任何结果,直到我在应用的过滤器 VBA 上手动单击确定,一旦我这样做它就会显示正确的结果我在这里错过了一个技巧吗?
Sub FilterListOrTableData()
Dim ACell As Range
Dim ActiveCellInTable As Boolean
Dim FilterCriteria As String
Dim Created As String
Dim sToday As String
Dim sStartDate As String
Dim dStartDate As Date
Dim sUpperBound, sLowerBound As String
'Check to see if the worksheet is protected.
If ActiveSheet.ProtectContents = True Then
MsgBox "This macro will not work when the worksheet is write-protected.", _
vbOKOnly, "Filter example"
Exit Sub
End If
'Set a reference to the ActiveCell named ACell. You can always use
'ACell now to point to this cell, no matter where you are in the workbook.
Set ACell = ActiveCell
'Test to see if ACell is in a table or list. Note that by using ACell.ListObject, you
'don't need to know the name of the table to work with it.
On Error Resume Next
ActiveCellInTable = (ACell.ListObject.Name <> "")
On Error GoTo 0
'If the cell is in a list or table, run the code.
If ActiveCellInTable = True Then
'Show all data in the table or list.
On Error Resume Next
ActiveSheet.ShowAllData
On Error GoTo 0
'This example filters on the first column in the List/Table
'(change the field if needed). In this case the Table starts
'in A so Field:=1 is column A, field 2 = column B, ......
'Use "<>" & filtercriteria if you want to exclude the criteria from the filter.
'FilterCriteria = InputBox("What text do you want to filter on?", _
' "Type in the filter item.")
' ACell.ListObject.Range.AutoFilter _
' Field:=1, _
' Criteria1:="=" & FilterCriteria
'This example filters on the ActiveCell value.
'ACell.ListObject.Range.AutoFilter _
' Field:=ACell.Column - ACell.ListObject.Range.Cells(1).Column + 1, _
' Criteria1:="=" & ACell.Text
sToday = Date
dStartDate = DateValue(Date) - 7
sStartDate = Str(dStartDate)
sLowerBound = ">=" + sStartDate
sUpperBound = "<=" + sToday
ACell.ListObject.Range.AutoFilter Field:=89, Criteria1:=sLowerBound, _
Operator:=xlOr, Criteria2:=sLowerBound
ActiveWorkbook.RefreshAll
'Else
' MsgBox "Select a cell in your list or table before you run the macro.", _
'vbOKOnly, "Filter example"
End If
End Sub
这是我执行手动选项时宏记录的内容:
Sub Macro1()
'
' Macro1 Macro
'
'
ActiveSheet.ListObjects("FTLOG").Range.AutoFilter Field:=84, Criteria1:= _
">=29/11/2016", Operator:=xlOr, Criteria2:=">=29/11/2016"
End Sub
【问题讨论】:
-
通过代码的过滤器是在activecell的基础上生成的。例如,单击要过滤的行并运行它。
-
是的,要让按钮工作,我必须先选择表格中的任何单元格才能工作,稍后我会将其更改为设定值,目前代码工作但没有显示任何内容,直到我点击VBA创建的客户过滤器,然后当我点击确定它显示所有正确的结果时,这个问题让我完全困惑。
-
能给几张截图吗?看起来很有趣
-
只能添加 1 个屏幕截图,因此添加了一个我手动进入客户过滤器 VBA 应用,当我点击确定时,表格从空到显示正确结果
-
对不起,我还是不明白。那么,使用您的代码,您会得到一个过滤器,但数据没有被过滤?尝试从代码中删除
ActiveWorkbook.RefreshAll。