3

So I have a loop that checks every cell in a column and finds a specific date (currently the Monday of the previous week). My code right now does select them correctly but I want it to keep the previous selection so in the end all cells of that specification are selected

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

As a bonus, to change the Function to a different day of last week would I simply change the vbMonday to vbTuesday etc? I admit I don't know VBA very well and most of this is just frankensteined from around here.

Le Ish Man
  • 451
  • 2
  • 4
  • 20

1 Answers1

17

The best way to do that is to store all the cells in a range using the Union Method.

Also I wouldn't recommend using .Select. You may want to see THIS

Amend your code to add this code.

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

One more thing... Please note that xlDown should be avoided as much as possible. You may want to see THIS

Community
  • 1
  • 1
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250