簡體   English   中英

如何在Excel VBA中添加當前單元格選擇

[英]How to add to current cell selection in Excel VBA

所以我有一個循環,它檢查列中的每個單元格並找到一個特定的日期(當前是前一周的星期一)。 我的代碼現在確實正確地選擇它們但是我希望它保留先前的選擇,所以最后選擇該規范的所有單元格

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更改為vbTuesday等嗎? 我承認我不太了解VBA,而且大部分都只是來自這里的frankensteined。

最好的方法是使用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 你可能想看看這個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM