首页 > 解决方案 > 在 2 个范围之间选择数据

问题描述

我在执行循环以在 2 个范围之间选择数据时遇到了一些问题。我有 2 个值: 2020-04-01 inRange("E2")和 2020-06-01 in Range("E4")。在此之后,我正在寻找这两个日期column A,但遇到了一些困难。可以通过以下方式选择两个范围:

Sub FindDate()

    Dim date1 As String, date2 As String
    Dim date1Cell As Range, date2Cell As Range, valRng As Range
    Dim i As Long

    Set valRng = Range("A1:A1000")
    date1 = Format(Range("E2"), "yyyy-mm-dd")
    date2 = Format(Range("E4"), "yyyy-mm-dd")

    Set date1Cell = Cells.Find(What:=CDate(date1), After:=Range("A1"), LookIn:=xlFormulas _
            , LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
        'date1Cell.Select
    Set date2Cell = Cells.Find(What:=CDate(date2), After:=Cells(date1Cell), LookIn:=xlFormulas _
            , LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
        'date2Cell.Select
    For i = date1Cell To date2Cell
    ------------------------    ------------------------    ------------------------
        'How do I set up that loop to search and select from date1Cell to date2Cell
    ------------------------    ------------------------    ------------------------
    Next i

End Sub

标签: excelvba

解决方案


一个使用循环而不是循环的简短示例Find

Sub dural()
    Dim date1 As String, date2 As String, cell As Range
    Dim date1Cell As Range, date2Cell As Range, valRng As Range
    Dim i As Long

    Set valRng = Range("A1:A1000")
    date1 = Format(Range("E2"), "yyyy-mm-dd")
    date2 = Format(Range("E4"), "yyyy-mm-dd")

    For Each a In valRng
        If a.Text = date1 Then Set date1Cell = a
        If a.Text = date2 Then Set date2Cell = a
    Next a

    Range(date1Cell, date2Cell).Select
End Sub

在此处输入图像描述

笔记:

您不需要循环来进行实际选择。


推荐阅读