Home » excel » excel – How to write a macro to filter a column and take out the required value?

excel – How to write a macro to filter a column and take out the required value?

Posted by: admin May 14, 2020 Leave a comment


I need a macro that need to filter a column and to take out the required date value along with the cell position (i.e say “4/22/2018” cell position “A9 or just 9”). Kindly help me out to fix this issue

See the code that I wrote below

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

How to&Answers:

Is this what you are trying?

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


The following will filter the dates and for each date it will copy the value into Sheet Log in Column 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.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