我有一个宏,我在其中创建了一些工作表,这些工作表的名称取自列c中的值,单元格7以及名为" Schedule"的工作表。我正在使用以下代码
Sub CreateDataSheets()
'Updateby Extendoffice 20161215
Dim xRg As Variant
Dim wSh As Excel.Worksheet
Dim wBk As Excel.Workbook
Set wSh = ActiveSheet
Set wBk = ActiveWorkbook
Application.ScreenUpdating = False
For Each xRg In wSh.Range("C7", Range("C7").End(xlDown))
If Not IsError(xRg) Then
If xRg <> "" Then
If Not WorksheetExists((xRg)) Then
With wBk
.Sheets.Add after:=.Sheets(.Sheets.Count), Type:="L:\London\General\Reference & Tools\Software\BIM\IiA_Specifications\Excel\Uk Specification Template.xltx"
ActiveSheet.Name = xRg.Value
End With
End If
End If
End If
Next xRg
Application.ScreenUpdating = True
End Sub
现在我需要另一个宏,如果我在C列中更改或删除任何这些值,我想创建新的更新的并删除所有冗余的表。在执行此操作时,我想保留名为Schedule,Home和CoverSheet的工作表。下面是我尝试编写的代码,但这不起作用。
Sub DeleteNewSheets()
Dim ws As Worksheet
Dim ArrayOne() As Variant
Dim wsName As Variant
Dim Matched As Boolean
Dim DirArray As Variant
DirArray = Range("C7:C11")
ArrayOne = Array("Home", "Schedule", "CoverSheet", DirArray.Value)
Application.DisplayAlerts = False
For Each ws In Sheets
Matched = False
For Each wsName In ArrayOne
If wsName = ws.Name Then
Matched = True
Exit For
End If
Next
If Not Matched Then
ws.Delete
End If
Next ws
Application.DisplayAlerts = True
End Sub
非常感谢任何想法...
答案 0 :(得分:1)
DirArray
创建为Variant
,数组4
的位置ArrayOne
实际上是另一个数组,而不是字符串。
要解决此问题,请按以下方式初始化ArrayOne
:
ArrayOne = Array("Home", "Schedule", "CoverSheet")
Dim Name As Variant
For Each Name In DirArray
If Name <> "" Then
ReDim Preserve ArrayOne(UBound(ArrayOne) + 1)
ArrayOne(UBound(ArrayOne)) = Name
End If
Next
它也不会考虑您所选范围的空值。
请考虑更改Sam's answer
上的删除步骤答案 1 :(得分:0)
迭代更改集通常是一个坏主意。做这样的事情
For i = Sheets.Count to 1 Step -1
If ....
Sheets(i).Delete
End If
Next i