Excel VBA:对于列中的每个单元格 A3:A 如果函数

Excel VBA: For Each Cell In Column A3:A If Functions

我有一个列表框,我试图根据列中的每个单元格填充它 A3:A If CDate(Cell.Value) < 2 Years.

基本上是查看 A3 列直到最后一次使用单元格的日期小于 2 年到相邻 B 列的 return 值(如果 ListBox 为真)。

谢谢。

 Dim MyDateYear As Date
 Dim Cell As Range

 MyDateYear = Date
 MyDateYear = DateAdd("m", -24, MyDateYear)

 For Each Cell In Worksheets("Sheet1").UsedRange.Columns("A").Cells
 If CDate(Cell.Value) < Format(MyDateYear, "YYYY") Then
 Me.ListBox1.AddItem Cells(Cell.Row, 2).Value
 End If

 Next Cell

试试这个

Dim MyDateYear As Date
Dim Cell As Range
Dim LRow as Long

MyDateYear = Date
MyDateYear = DateAdd("m", -24, MyDateYear)

With Workbooks(REF).Sheets("Sheet1") 'edit reference
    LRow = .Cells(.Rows.Count, "A").End(xlUp).Row

    For Each Cell In .Range("A3:A" & LRow)
        If CDate(Cell.Value) < Format(MyDateYear, "YYYY") Then
            Me.ListBox1.AddItem .Cells(Cell.Row, 2).Value
        End If
    Next Cell
End With

有关获取最后一个单元格、行、列的更多信息,请阅读this article