出现额外的工作表

时间:2013-12-17 03:03:34

标签: excel-vba vba excel

当我输入此函数生成新工作表并命名它时,我遇到了关于excel vba的一些问题。但它会产生额外的新工作表。以下是编码。

Function add_sheet_by_branch(ByVal branch As String) As String


    For rep = 1 To (Worksheets.Count)
        If LCase(Sheets(rep).name) = LCase(branch) Then
            MsgBox (branch & " " & "already exists!")
        Else
            Sheets.Add after:=Sheets(Sheets.Count)
        End If
    Next
    Sheets(ActiveSheet.name).name = branch
    Sheets.Delete
    add_sheet_by_branch = name
End Function

感谢您的帮助。 :)

1 个答案:

答案 0 :(得分:0)

这是你在尝试的吗?

每次工作表名称不匹配时,您都在创建工作表。

Function add_sheet_by_branch(ByVal branch As String) As String
    Dim ws As Worksheet

    On Error Resume Next
    Set ws = ThisWorkbook.Sheets(branch)
    On Error GoTo 0

    If ws Is Nothing Then
        ThisWorkbook.Sheets.Add _
        after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
        ActiveSheet.Name = branch
        add_sheet_by_branch = Name
    Else
        MsgBox (branch & " " & "already exists!")
    End If
End Function