单击为每个时间按钮添加新Excel工作表的循环

时间:2018-02-19 13:38:44

标签: vba excel-vba excel

我尝试在每次点击按钮时添加新的Excel,因为工作表是在日期之后命名的。但是,我收到一条错误,上面写着"无法将工作表重命名为与另一个工作表相同的名称,引用的对象库或Visual Basic引用的工作簿。"

Dim szTodayDate As String
szTodayDate = Format(Date, "mm.dd")
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets.Add(After:= _
         ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
ws.Name = szTodayDate

我想要的是创建一个名为mm.dd.i的新工作表。虽然我指的是使用按钮创建新工作表的时间。对不起,我是VBA的新手。

感谢您的回答。加里的学生做得最有效率。解决。

3 个答案:

答案 0 :(得分:3)

怎么样:

Sub sjvyv()
    Dim szTodayDate As String
    szTodayDate = Format(Date, "mm.dd")
    Dim ws As Worksheet, i As Long
    ReDim N(1 To Sheets.Count)

    i = 1
    For Each ws In Sheets
        If Left(ws.Name, 5) = szTodayDate Then
            N(i) = Mid(wsname, 6)
            i = i + 1
        End If
    Next ws

    Set ws = ThisWorkbook.Sheets.Add(After:= _
             ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
    ws.Name = szTodayDate & "." & i
End Sub

答案 1 :(得分:1)

以下是为表单创建新名称的代码段:

Sub AddSheet()
    Dim TodayDate As String
    Dim i As Integer
    TodayDate = Format(Date, "mm.dd")
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets.Add(After:= _
             ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))

    i = 1

    Do While Not SheetNameAvailable(TodayDate & "." & i)
        i = i + 1
    Loop

    ws.Name = TodayDate & "." & i
End Sub

Function SheetNameAvailable(SheetName As String) As Boolean
    Dim ws As Worksheet
    On Error Resume Next
    Err.Clear
    Set ws = ThisWorkbook.Worksheets(SheetName)
    SheetNameAvailable = (Err.Number <> 0)
    On Error GoTo 0
End Function

答案 2 :(得分:0)

On Error Resume Next
Set tempWS = Sheets(szTodayDate)

ws.Name = szTodayDate & IIf(tempWS Is Nothing, "", GetSheetCount(szTodayDate))

Set tempWS = Nothing

On Error GoTo 0
Function GetSheetCount(dateToTest) As Integer
    Dim i As Integer

    i = 1

    For Each sh In ThisWorkbook.Sheets
        If sh.Name Like dateToTest & "*" Then
            i = i + 1
        End If
    Next

    GetSheetCount = i
End Function


ws.Name = szTodayDate & ThisWorkbook.Sheets.Count + 1

只需将张数(+1)附加到最后。