如何编写宏来过滤列并取出所需的值?

时间:2018-04-17 09:32:51

标签: excel excel-vba filter excel-2010 autofilter vba

我需要一个宏,需要过滤一个列并取出所需的日期值以及单元格位置(即“4/22/2018”单元格位置“A9或仅9”)。请帮我解决这个问题

请参阅我在下面写的代码

Dim Date As String

Date = Sheets("alldata")
Rows("3:3").Select.AutoFilter.Range("$A$3:$AA$606").AutoFilter , Field:=1, Criterial:="#VALUE!"
Range("A3").Select.xlFilterValues.offset(1, 0).Copy.value

Sheets("Log").Cells(2, "AF").value = Date

problem snapshot

2 个答案:

答案 0 :(得分:2)

这是你在尝试的吗?

Sub Sample()
    Dim ws As Worksheet
    Dim rng As Range

    Set ws = Sheets("alldata")

    With ws
        Set rng = .Range("$A$3:$A$606")

        '~~> Remove any filters
        .AutoFilterMode = False

        With rng
            .AutoFilter Field:=1, Criteria1:="<>#VALUE!"

            '~~> Get the Row Number
            MsgBox .Offset(1, 0).SpecialCells(xlCellTypeVisible).Row

            '~~> Get The cell Address
            MsgBox .Offset(1, 0).SpecialCells(xlCellTypeVisible).Cells(1, 1).Address

            '~~> Get the Date
            Sheets("Log").Cells(2, "AF").Value = _
            .Offset(1, 0).SpecialCells(xlCellTypeVisible).Cells(1, 1).Value
        End With

        '~~> Remove any filters
        .AutoFilterMode = False
    End With
End Sub

答案 1 :(得分:0)

以下内容将过滤日期以及将值复制到列AF的工作表日志中的每个日期:

Sub foo()
Dim ws As Worksheet: Set ws = Sheets("alldata")
Dim wsLog As Worksheet: Set wsLog = Sheets("Log")
'declare and set your worksheet, amend as required
Dim LastRow As Long, LogLastRow As Long
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'get the last row with data on Column A
Dim c As Range, rng As Range

    ws.Rows("3:3").AutoFilter
    ws.Range("$A$3:$AA$" & LastRow).AutoFilter Field:=1, Operator:=xlFilterValues, Criteria2:=Array(0, "01/01/2018")
    Set rng = ws.Range("$A$4:$A$" & LastRow).SpecialCells(xlCellTypeVisible)

    For Each c In rng
        LogLastRow = wsLog.Cells(wsLog.Rows.Count, "AF").End(xlUp).Row
        c.Copy Destination:=wsLog.Cells(LogLastRow, "AF")
        'if instead of copying the value, you want to return its address,
        'you can get the address by using "c.Address" for each value in the range
    Next c
End Sub