我是VBA Excel的新手。我运行一个大型的月度报告,并且希望使该报告自动化,以减少人工时间。当我打开报告时,报告当前显示上个月的信息(最终,我将提取更新的信息到报告中)。我正在寻找一个自动化的过程,并编写一个脚本,该宏运行后将自动隐藏上个月的标签并打开当前月份的标签。
例如:我正在运行2018年9月的报告。打开该报告,可见的选项卡显示“ Aug18”。我希望运行一个宏,该宏将自动隐藏“ Aug18”选项卡,并且不隐藏“ Sep18”选项卡。任何帮助将不胜感激。谢谢!
答案 0 :(得分:1)
1)将当前日期转换成可用于测试“大于”类型逻辑YYYYMM的格式:
Dim currentDate As String
currentDate=Format(Now(), "YYYYMM")
2)循环浏览工作表:
Dim currentDate As String
currentDate=Format(Now(), "YYYYMM")
Dim ws as Worksheet
For Each ws in ThisWorkbook.Worksheets
Next ws
3)在该循环内,转换测试是否为一个名为月份的工作表。在此处使用InStr
:
Dim currentDate As String
currentDate = Format(Now(), "YYYYMM")
Dim ws As Worksheet
Dim thisTabDate As String
For Each ws In ThisWorkbook.Worksheets
'Test to see if this is in the right format
If InStr(1, "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec", Left(ws.Name, 3)) Then
End If
Next ws
4)如果是,则将标签页的名称格式设置为与YYYYMM相同,并设置其可见性
Dim currentDate As String
currentDate = Format(Now(), "YYYYMM")
Dim ws As Worksheet
Dim thisTabDate As String
For Each ws In ThisWorkbook.Worksheets
'Test to see if this is in the right format
If InStr(1, "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec", Left(ws.Name, 3)) Then
'This is messy, but we are just cutting the tab name up, turning it into an actual date, and then formatting that.
thisTabDate = Format(CDate(Left(ws.Name, 3) & "-01-" & Right(ws.Name, 2)), "YYYYMM")
'Set the visible True/False to the result of the test
ws.Visible = (thisTabDate >= currentDate)
End If
Next ws