Macro excel to create new sheets with names based on a list BUT if repeated do not create

元气小坏坏 提交于 2019-12-12 02:32:29

问题


I am able to create sheets including its name based on a selected list of "names" with the following code (below), BUT when there are cells with repeated name it will create a sheet without a name and the generic "sheet##". I want that if the cell name is repeated or there is a sheet already with that name (same thing) NOT to create a new sheet.

Sub AddSheets()
Dim cell As Excel.Range
Dim wbToAddSheetsTo As Excel.Workbook

Set wbToAddSheetsTo = ActiveWorkbook
For Each cell In Selection
With wbToAddSheetsTo
    .Sheets.Add after:=.Sheets(.Sheets.Count)
    On Error Resume Next
    ActiveSheet.Name = cell.Value
    If Err.Number = 1004 Then
      Debug.Print cell.Value & " already used as a sheet name"
    End If
    On Error GoTo 0
End With

End Sub

回答1:


Check to see if the worksheet exists before creating it:

Public Function WorkSheetExists(SheetName As String, wrkbk As Workbook) As Boolean
    Dim wrkSht As Worksheet
    On Error Resume Next
        Set wrkSht = wrkbk.Worksheets(SheetName) 'Attempt to set reference to worksheet.
        WorkSheetExists = (Err.Number = 0) 'Was an error generated - True or False?
        Set wrkSht = Nothing
    On Error GoTo 0
End Function

Then in your code just check if it exists before creating it:

Sub AddSheets()
    Dim cell As Excel.Range
    Dim wbToAddSheetsTo As Excel.Workbook

    Set wbToAddSheetsTo = ActiveWorkbook
    For Each cell In Selection
        **If Not (WorkSheetExists(cell.Value, wbToAddSheetsTo)) Then**
            With wbToAddSheetsTo
                .Sheets.Add after:=.Sheets(.Sheets.Count)
                On Error Resume Next
                ActiveSheet.Name = cell.Value
                If Err.Number = 1004 Then
                  Debug.Print cell.Value & " already used as a sheet name"
                End If
                On Error GoTo 0
            End With
        **End If**
    Next cell

End Sub


来源:https://stackoverflow.com/questions/29678539/macro-excel-to-create-new-sheets-with-names-based-on-a-list-but-if-repeated-do-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!