简体   繁体   English

使用VBA删除工作簿中的第二页和第三页

[英]Delete every second and third sheet in a workbook using VBA

Im looking to delete second and third sheet in a workbook with hundreds of sheets. 我希望删除具有数百个工作表的工作簿中的第二张和第三张纸。 So, keep sheets 1,4,7,10... and delete the rest 因此,保留工作表1,4,7,10 ...,然后删除其余部分

I'm running into issues because the indices reset with every sheet I delete so looping with i's is presenting a problem. 我遇到了问题,因为索引随着我删除的每个工作表而重置,因此与我的循环出现了问题。

Any ideas? 有任何想法吗?

Thanks! 谢谢!

RGA is right you should loop from last to first when deleting. RGA是正确的,删除​​时应该从最后到第一个循环。 Index mod 3 will return 1 for 1, 4, 7, 10 , 13, 16 .ect. 索引mod 3将针对1、4、7、10、13、16等返回1。

Sub DeleteEvery2ndAnd3rdSheet()
   Application.DisplayAlerts = False

    Dim i As Integer
    For i = Worksheets.Count To 1 Step -1
        If i Mod 3 <> 1 Then Worksheets(i).Delete
    Next

    Application.DisplayAlerts = True

End Sub

While Thomas' answer may be the way to go, here is another approach that will only run the Delete statement once. 尽管托马斯的答案可能是解决之道,但这是另一种只运行一次Delete语句的方法。

Sub Delete2nd3rdSheets()

Dim sSheetsToRemove As String
Dim i As Integer

Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets

    If ws.Index Mod 3 <> 1 Then
        sSheetsToRemove = sSheetsToRemove & "," & ws.Name
    End If

Next

sSheetsToRemove = Mid(sSheetsToRemove, 2)

Dim arrDeleteSheets() As String
arrDeleteSheets = Split(sSheetsToRemove, ",")

Application.DisplayAlerts = False
Worksheets(arrDeleteSheets).Delete
Application.DisplayAlerts = True

End Sub

Loop from the end to the beginning instead of beginning to end (always good practice when deleting things from a list in any coding language) 从头到尾循环,而不是从头到尾循环(从任何编码语言的列表中删除内容时,总是一个好习惯)

Just keep a counter running as you go that counts up to three and resets, making sure first that it is set properly to act on the last sheet (aka figure out with math whether that last sheet would be a "1st", "2nd", or "3rd" sheet) 只需保持计数器运行即可,最多可计数三个并重置,首先要确保将其正确设置为对最后一张纸起作用(也可以通过数学计算得出最后一张纸是“ 1st”还是“ 2nd”)或“第3个”工作表)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM