[英]Excel - macro to select cell in workbook with current date
我正在 Excel 中創建日歷/計划工作簿。 每個月都有一個工作表。
現在我需要創建一個CommandButton
,它將我帶到包含當前日期的單元格。 只有一個具有當前日期的單元格,但它可以位於工作簿的任何工作表上。
我已經找了好幾天了,但還是找不到!
我一直在嘗試的事情:
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
當具有當前日期的單元格在同一張紙上時(盡管它一直重新選擇單元格直到我按 Esc 鍵),這有點有效,但是當單元格在另一張紙上時會失敗。
任何幫助,將不勝感激!
我認為您不需要 Do While 循環。 由於您只是在尋找一個,這個簡單的 For/Next 應該可以。 找到后,代碼退出循環並轉到最后的 Select 部分。 如果未找到日期,則不選擇任何內容:
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
請注意,在選擇范圍之前,您需要激活父工作表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.