如何在列中查找特定月份和年份的行

时间:2017-08-18 12:42:28

标签: excel vba excel-vba

我遇到了一个小问题,下面的pay out date列的日期格式为dd/mm/yyyy。因为我想找到特定月份和年份的行 - 例如哪一行包含10-2017。

Pay out Date
12-05-2016
18-05-2016
22-06-2016
20-07-2016
24-08-2016
21-09-2016
19-10-2016
23-11-2016
21-12-2016
18-01-2017
22-02-2017
22-03-2017
19-04-2017
24-05-2017
21-06-2017
19-07-2017
23-08-2017
20-09-2017
18-10-2017
22-11-2017
20-12-2017
24-01-2018
21-02-2018
24-03-2018

在正常的Excel + Ctrl + F中给出月份和年份(10-2017)确切地找到它是哪一行但是通过代码没有工作 - 任何建议都将不胜感激

Sub find()
Dim c1 As Range
Dim cd As Long
 Set c = ThisWorkbook.Sheets(1).Range("A2:A60").find(What:="10-2017", After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)

cd = c.Row

  Debug.Print (cd)

End Sub

1 个答案:

答案 0 :(得分:1)

这将查找一个月中包含的日期

Public Sub FindDateInRange()
    Dim rng As Range
    Dim dat As String
    Dim begMonth As Long, endMonth As Long
    Dim c

    Set rng = ThisWorkbook.Sheets(1).Range("A2:A60")

    dat = "10-2017"

    begMonth = DateSerial(Split(dat, "-")(1), Split(dat, "-")(0), 1)
    endMonth = Application.WorksheetFunction.EoMonth(begMonth, 0)

    For Each c In rng
        If c.Value2 >= begMonth And c.Value2 <= endMonth Then
            Debug.Print c.Row
        End If
    Next c
End Sub