如果尚不存在该如何创建工作表?

时间:2019-06-20 14:40:58

标签: excel vba

我正在使用以下代码在工作簿中检查sheet1sheet2是否存在。如果它们不存在,则应该生成它们。否则,什么也不会发生。

我的问题是,当两个工作表都不存在时,该宏仅适用于第一次迭代。创建工作表后,出现错误。诸如“名称已存在。选择其他名称…”之类的内容。如果sheet1sheet2已经存在,我不希望发生任何事情。

Sub Worksheet()

    Dim x As Integer, blnFound1 As Boolean, blnFound2 As Boolean
    blnFound1 = False
    blnFound2 = False

    With ThisWorkbook

        For x = 1 To .Sheets.Count

            If .Sheets(x).Name = "Sheet1" Then
                blnFound1 = True
                Exit For
            End If

            If .Sheets(x).Name = "Sheet2" Then
                blnFound2 = True
                Exit For
            End If

        Next x

        If blnFound1 = False Then
            .Sheets.Add
            With ActiveSheet
                .Name = "Sheet1"
            End With
        End If

        If blnFound2 = False Then
            .Sheets.Add
            With ActiveSheet
                .Name = "Sheet2"
            End With
        End If

    End With

End Sub

2 个答案:

答案 0 :(得分:4)

我在每个项目上使用一个不同的宏来处理此问题,因此您可以随时使用它:

Sub TestSheet(SheetName As String)

    Dim Exists As Boolean

    With ThisWorkbook
        On Error Resume Next
        Exists = (.Worksheets(SheetName).Name <> "")
        On Error GoTo 0
        If Not Exists Then
            .Sheets.Add After:=.Sheets(.Sheets.Count)
            .Sheets(.Sheets.Count).Name = SheetName
        End If
    End With

End Sub

这是您的测试方式:

Sub Test()

    TestSheet "Sheet1"
    TestSheet "Sheet2"

End Sub

答案 1 :(得分:0)

如果您只想在不存在新工作表的情况下使用呢?

在这种情况下,我将使用Try-Parse Pattern

为此,请创建一个使用工作表名称和一个ByRef参数的函数,该函数可以返回您新创建的工作表对象。

Public Function TryCreateWorksheet(ByVal SheetName As String, Optional ByRef outWorksheet As Worksheet, Optional ByRef Source As Workbook) As Boolean

    'If workbook not passed in then set it to the activeworkbook.
    If Source Is Nothing Then
        Set Source = ActiveWorkbook
    End If

    If Not WorksheetExists(SheetName, Source) Then

        'Return true, then set outWorksheet to created worksheet and rename it.
        TryCreateWorksheet = True
        Set outWorksheet = Source.Worksheets.Add(After:=Source.Worksheets(Source.Worksheets.Count))
        outWorksheet.Name = SheetName

    End If

End Function

这里是检查工作表是否存在的功能。最好明确指出要检查的Workbook,以免出现任何错误。

Public Function WorksheetExists(ByVal SheetName As String, ByRef Source As Workbook) As Boolean
    On Error Resume Next
    WorksheetExists = (Source.Worksheets(SheetName).Name <> "")
    On Error GoTo 0
End Function

如何使用它?

如果创建了工作表,则该函数返回true,您可以放心地知道您对新工作表有引用。

您可以在if语句中使用它来查看它是否返回true。如果是这样,您现在可以使用工作表对象。见下文:

Private Sub SomeProcedure()

    Dim CreatedWs As Worksheet
    If TryCreateWorksheet("Sheet3", CreatedWs, ActiveWorkbook) = False Then
        MsgBox "Sheet already exists", vbInformation
        Exit Sub
    End If

    'Do Something with your created Ws
    Debug.Print CreatedWs.Name

End Sub

如果工作表存在时想要一个唯一的名称怎么办?

在这种情况下,您可以在工作表名称的末尾添加唯一索引。

例如,如果您有Sheet1,则下一个唯一名称将是Sheet1 (2),依此类推。

Public Function UniqueSheetName(ByVal Name As String, ByRef Source As Workbook) As String

    'Used to create a new unique name
    Dim NewName As String
    NewName = Name

    'Used to increment the name index. ie: Sheet1(1)
    Dim Index As Integer
    Index = 1

NameLoop:

    'If exists then change name to include increment (n)
    If WorksheetExists(NewName, Source) Then
        Index = Index + 1
        NewName = Name & " (" & Index & ")"
        GoTo NameLoop
    End If

    UniqueSheetName = NewName

End Function