如何在Excel VBA中添加当前的单元格select

所以我有一个循环,检查列中的每个单元格,并find一个特定的date(目前是前一周的星期一)。 我现在的代码确实select了它们,但是我希望它能够保留之前的select,所以最终select了该规范的所有单元格

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 

作为一个奖励,将function更改为上周的不同日子,我会简单地将vbMonday更改为vbTuesday等? 我承认我不太了解VBA,而且大部分都是从这里开始的。

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

另外我不会推荐使用。select。 你可能想看到这个

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

 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 。 你可能想看到这个