Excel添加工作表或覆盖(如果存在)

在Excel中我有一个macros,将活动工作表的所有列转换为名为“MasterList”的新工作表

我的问题是,当我重新运行macros,我得到一个错误,说“这个名字已经被采取”。 尝试一个不同的。

如果它已经存在,我需要我的macros来覆盖MaterList工作表。

这是我的代码:

Sub ToArrayAndBack() Dim arr As Variant, lLoop1 As Long, lLoop2 As Long Dim arr2 As Variant, lIndex As Long 'turn off updates to speed up code execution With Application .ScreenUpdating = False .EnableEvents = False .Calculation = xlCalculationManual .DisplayAlerts = False End With ReDim arr2(ActiveSheet.UsedRange.Cells.Count - ActiveSheet.UsedRange.SpecialCells(xlCellTypeBlanks).Count) arr = ActiveSheet.UsedRange.Value For lLoop1 = LBound(arr, 1) To UBound(arr, 1) For lLoop2 = LBound(arr, 2) To UBound(arr, 2) If Len(Trim(arr(lLoop1, lLoop2))) > 0 Then arr2(lIndex) = arr(lLoop1, lLoop2) lIndex = lIndex + 1 End If Next Next Sheets.Add.Name = "MasterList" Range("A1").Resize(, lIndex + 1).Value = arr2 Range("A1").Resize(, lIndex + 1).Copy Range("A2").Resize(lIndex + 1).PasteSpecial Transpose:=True Rows(1).Delete With Application .ScreenUpdating = True .EnableEvents = True .Calculation = xlCalculationAutomatic .DisplayAlerts = True End With End Sub 

您可以将工作表创build在错误恢复和错误转到0之间。另一个解决scheme是循环遍历工作簿工作表集合,并检查是否存在具有该工作表的工作表。

解决scheme1:

 On Error Resume Next Sheets.Add.Name = "MasterList" On Error GoTo 0 

解决scheme2:

 Dim ws As Worksheet Dim found As Boolean found = False For Each ws In ThisWorkbook.Sheets If ws.Name = "MasterList" Then found = True Exit For EndIf Next If Not found Then Sheets.Add.Name = "MasterList" EndIf 

为了避免依赖MasterList是活动的事实:

 Set ws = ThisWorkbook.Sheets("MasterList") With ws .Range("A1").Resize(, lIndex + 1).Value = arr2 .Range("A1").Resize(, lIndex + 1).Copy .Range("A2").Resize(lIndex + 1).PasteSpecial Transpose:=True .Rows(1).Delete End With