Vba Excel添加工作表或覆盖(如果存在)
在excel中,我有一个宏,可以将活动工作表的所有列转换为名为“主列表”的新工作表 我的问题是,当我重新运行该宏时,会出现一个错误,显示“该名称已被使用”。请尝试其他名称 如果MaterList工作表已经存在,我需要宏来覆盖它 这是我的密码:Vba Excel添加工作表或覆盖(如果存在),vba,excel,Vba,Excel,在excel中,我有一个宏,可以将活动工作表的所有列转换为名为“主列表”的新工作表 我的问题是,当我重新运行该宏时,会出现一个错误,显示“该名称已被使用”。请尝试其他名称 如果MaterList工作表已经存在,我需要宏来覆盖它 这是我的密码: Sub ToArrayAndBack() Dim arr As Variant, lLoop1 As Long, lLoop2 As Long Dim arr2 As Variant, lIndex As Long 'turn off updates t
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
您可以将工作表创建置于出错恢复和出错转到0之间。另一种解决方案是循环遍历工作簿工作表集合,并检查是否存在具有该名称的工作表 解决方案1:
On Error Resume Next
Sheets.Add.Name = "MasterList"
On Error GoTo 0
解决方案2:
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
为避免依赖主列表处于活动状态的事实:
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
只是一个建议:如果它存在,你不能删除它并重新创建它吗?我想我不能,因为我将把它链接到MS Access。塔里克,谢谢你的建议。我是VBA的新手。您能告诉我这两种解决方案在我的代码中是什么样子的吗?解决方案1:首先它创建一个名为MasterList的工作表,然后创建一个新工作表。我需要列中的数据始终进入主列表。解决方案2:将所有列转换为活动工作表的第一列(即工作表订单号而非主列表)。这很好,但不完全是我需要的代码。您还可以检查解决方案1中的错误代码并删除主表。在解决方案2中,如果发现为真,您可以删除母版纸。塔里克,谢谢!解决方案2成功了!是否有方法将名为“OrderNumber”的工作表中的列与活动工作表中的列合并?