问题
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