简体   繁体   中英

Excel - macro to select cell in workbook with current date

I'm creating a calendar/schedule workbook in Excel. It has a worksheet for each month.

Now I need to create a CommandButton which takes me to the cell which contains the current date. There's only one cell with the current date, but it can be on any sheet of the workbook.

I've been searching for days now, but can't get it right!

Things I've been trying:

Private Sub CommandButton1_Click()

Dim Sh As Worksheet
Dim Loc As Range

For Each Sh In ThisWorkbook.Worksheets
    With Sh.UsedRange
        Set Loc = .Cells.Find(What:=Int(Date), LookIn:=xlValues)
        If Not Loc Is Nothing Then
            Do Until Loc Is Nothing
                Loc.Select
                Set Loc = .FindNext(Loc)
            Loop
        End If
    End With
    Set Loc = Nothing

Next

End Sub

This kinda works when the cell with the current date is on the same sheet (although it keeps reselecting the cell until I press Esc), but fails when the cell is on another sheet.

Any help would be appreciated!

I don't think you need a Do While loop. Since you're only looking for the one, this simple For/Next should do. Once it's found the code exits the loop and goes to the Select section at end. If the date isn't found nothing is selected:

Private Sub CommandButton1_Click()
Dim Sh As Worksheet
Dim Loc As Range

For Each Sh In ThisWorkbook.Worksheets
    With Sh.UsedRange
        Set Loc = .Cells.Find(What:=Int(Date), LookIn:=xlValues)
        If Not Loc Is Nothing Then
            Exit For
        End If
    End With
Next
If Not Loc Is Nothing Then
    'need to activate parent sheet before selecting cell
    Loc.Parent.Activate
    Loc.Select
End If
End Sub

Note that before you can select a range you need to activate the parent sheet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM