添加带有日期作为名称的工作表

时间:2018-09-29 16:29:31

标签: excel vba

我想添加一张纸并将其命名为今天的日期。如果该日期已经过,则接下来的下一个空闲日期。

宏适用于第一轮和第二轮。当我第三次运行它时,出现错误:

  

“工作表名称已存在”

我正在使用以下代码。

Sub datesheets()

    Dim found As Boolean
    Dim w As Worksheet 

    For Each w In Worksheets
        If w.Name = Format(Now(), "dd.mm.yyyy") Then
            found = True
            shname = Format(DateAdd("d", 1, Now()), "dd.mm.yyyy")
            Worksheets.Add(, w).Name = shname
        End If
    Next w

    If found = False Then
        Worksheets.Add(, ActiveSheet).Name = Format(Now(), "dd.mm.yyyy")
    End If

End Sub

1 个答案:

答案 0 :(得分:2)

尝试此解决方案。将今天的日期声明为最大日期,然后将其与工作表进行比较以查找是否存在日期大于或等于该工作表的工作表。如果是这样,则更大的日期将递增。

Sub addNextDateSheet()

    Dim found As Boolean
    Dim sheet As Worksheet
    Dim biggestDate As Date

    biggestDate = Date

    For Each sheet In Worksheets
        'checking if the name is date
        If IsDate(Replace(sheet.Name, ".", "/")) Then
            'checking if the name is same as today or bigger
            If CDate(Replace(sheet.Name, ".", "/")) >= biggestDate Then
                'increment date if it is the same or bigger
                biggestDate = CDate(Replace(sheet.Name, ".", "/")) + 1
            End If
        End If
    Next sheet

    'add new sheet
    Worksheets.Add(ActiveSheet).Name = Format(biggestDate, "dd.mm.yyyy")

End Sub

感谢@ newacc2240的反馈-非常有用。