[英]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.