如何在Excel VBA中添加到当前单元格选择

如何在Excel VBA中添加到当前单元格选择,vba,excel,Vba,Excel,因此,我有一个循环,检查列中的每个单元格,并找到一个特定的日期(当前为前一周的星期一)。我的代码现在确实正确地选择了它们,但我希望它保留以前的选择,以便最终选择该规范的所有单元格 Public Function LastMonday(pdat As Date) As Date LastMonday = DateAdd("ww", -1, pdat - (Weekday(pdat, vbMonday) - 1)) End Function Sub Macro2() Macro

因此,我有一个循环,检查列中的每个单元格,并找到一个特定的日期(当前为前一周的星期一)。我的代码现在确实正确地选择了它们,但我希望它保留以前的选择,以便最终选择该规范的所有单元格

Public Function LastMonday(pdat As Date) As Date
        LastMonday = DateAdd("ww", -1, pdat - (Weekday(pdat, vbMonday) - 1))
End Function

Sub Macro2()

 Macro2 Macro



Dim rng As Range
Dim curCellValue As String
Dim mondayStr As String

mondayStr = Format(LastMonday(Date), "dd/mm/yyyy")

Set rng = Range(ActiveSheet.Range("E2"), ActiveSheet.Range("E2").End(xlDown))

For Each Cell In rng
    curCellValue = Cell.Value
    If curCellValue = mondayStr Then Cell.Select
Next Cell

End Sub

作为奖励,若要将函数更改为上周的另一天,我是否只需将vbMonday更改为VB周二等?我承认我对VBA不太了解,其中大部分都是来自这里的科学怪人。

最好的方法是使用
联合方法将所有单元格存储在一个范围内

另外,我不建议使用
。选择
。你可能想看看

修改您的代码以添加此代码

Dim MySel As Range

For Each cell In Rng
    If cell.Value = mondayStr Then
        If MySel Is Nothing Then
            Set MySel = cell
        Else
            Set MySel = Union(MySel, cell)
        End If
    End If
Next cell

If Not MySel Is Nothing Then
    With MySel
        '.Select
        '~~> Do something
    End With
End If

还有一件事。。。请注意,应尽可能避免
xlDown
。您可能希望看到

像一个魔咒一样工作,并用链接中建议的方法替换xlDown。