使用for循环自动过滤后没有获得所有行的值

时间:2013-10-21 04:08:26

标签: excel-vba vba excel

我正在努力编写代码 - 下面的查询请帮助任何人编写代码。

  TestDataSheetName = ActiveWorkbook.Worksheets(x).Name
  ActiveWorkbook.Worksheets(x).Activate


CountTestData = ActiveWorkbook.Worksheets(x).Range("A" & Rows.Count).End(xlUp).Row
Range("A10").Select
Range("A10").AutoFilter
Selection.AutoFilter Field:=14, Criteria1:=">=" & DateToday


ActiveWorkbook.Worksheets(x).Activate
CountTestDataAftFilter = ActiveWorkbook.Worksheets(x).Range("A1", Range("A65536").End(xlUp)).SpecialCells(xlCellTypeVisible).Count


MsgBox CountTestDataAftFilter     
For w = 10 To CountTestDataAftFilter

      Set Foundcell1 = ActiveWorkbook.Worksheets(x).Cells.Find(What:=DateToday, After:=[ActiveCell], _
                    SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                    LookIn:=xlValues, LookAt:=xlPart, MatchCase:=True)                     
Next 
在使用今天的日期过滤后,我获得了5行今天的日期,我已经为获取所有行值而编写了循环,但是在找到第一行后,它没有找到第二行值,而是再次从第一行开始< / p>

请帮我解决上述代码。

感谢和安培;此致 岜

2 个答案:

答案 0 :(得分:0)

您正在寻找.FindNext功能。尝试这样的事情:(请注意,您可能需要稍微修改此代码以适合您的特定情况。)

Sub UseFindNext()

Dim TestDataSheet As Worksheet
Dim FoundCell1 As Range
Dim DateToday As Date
Dim firstAddress As String
Dim x As Long
Dim CountTestData As Long
Dim CountTestDataAftFilter As Long

x = 1

Set TestDataSheet = ActiveWorkbook.Worksheets(x)

CountTestData = TestDataSheet.Range("A" & Rows.count).End(xlUp).Row
Range("A10").AutoFilter Field:=14, Criteria1:=">=" & DateToday

CountTestDataAftFilter = TestDataSheet.Range("A1", Rows.count).End(xlUp)).SpecialCells(xlCellTypeVisible).count

Set FoundCell1 = TestDataSheet.Cells.Find(What:=DateToday, After:=TestDataSheet.Range("A10"), _
        SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        LookIn:=xlValues, LookAt:=xlPart, MatchCase:=True)
firstAddress = FoundCell1.Address
Do
    'Do whatever you're looking to do with each cell here. For example:
    Debug.Print FoundCell1.Value
Loop While Not FoundCell1 Is Nothing And FoundCell1.Address <> firstAddress

End Sub

答案 1 :(得分:0)

我不知道为什么你要经历每个价值。
您已使用AutoFilter来获取所需的数据。

但这是另一种可能对你有用的方法。

Sub test()

Dim ws As Worksheet
Dim wb As Workbook
Dim DateToday As String 'i declared it as string for the filtering
Dim rng, cel As Range
Dim lrow As Long

Set wb = ThisWorkbook
Set ws = wb.Sheets(x)

DateToday = "Put here whatever data you want" 'put value on your variable

With ws
    lrow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("N10:N" & lrow).AutoFilter Field:=1, Criteria1:=DateToday
    'I used offset here based on the assumption that your data has headers.
    Set rng = .Range("N10:N" & lrow).Offset(1, 0).SpecialCells(xlCellTypeVisible)
    'here you can manipulate the each cell values of the currently filtered range
    For Each cel In rng
        cel.EntireRow 'use .EntireRow to get all the data in the row and do your stuff
    Next cel
    .AutoFilterMode = False
End With

End Sub

BTW,这是基于this帖子,您可能还需要检查以改进编码 这是一个很好的阅读。希望这会有所帮助。