VBA代码,用于对名称未知的所有工作表和工作簿执行操作

时间:2016-07-07 22:11:50

标签: excel excel-vba vba

我有很多报道说我们都不需要小计。它们都是一个唯一的数字,然后是#34; Total"(粗体)。我正在尝试创建将应用于我的所有工作簿的代码,因为我创建了新的代码,它将查找并删除其中包含" Total"(粗体)文本的任何行。我知道如何将它应用于具有我知道的名称的特定工作簿/工作表,但不知道如何将它应用于任何带有任何名称的工作表。

    Sub Find_Delete_Total()
    Dim Total_Row As Long
    Dim X As Long

    For Each Ws In ActiveWorkbook.Worksheets


     With Ws
            With Application.FindFormat.Font
                .FontStyle = "Bold"
                .Subscript = False
                .TintAndShade = 0
            End With
            For X = 1 To 10000



        Total_Row = Cells.Find(What:="Total", _
                After:=Range("A1"), _
                LookAt:=xlPart, _
                LookIn:=xlFormulas, _
                SearchOrder:=xlByRows, _
                SearchDirection:=xlPrevious, _
                MatchCase:=False).Select.Row
                    Selection.Delete Shift:=xlUp

            Next X
        End With
    Next Ws

End Sub

2 个答案:

答案 0 :(得分:2)

您修改的代码缺少与End With对应的With ActiveSheet。另外,将ActiveSheet更改为Sht,并将限定 Cells.Find中的相应对象。

我做了一些修改,以避免在" total"找不到。

Sub Find_Delete_Total()
Dim Total_Row As Long
Dim X As Long
Dim delRow as Range
Dim Sht as Worksheet

For Each Sht In ActiveWorkbook.WorkSheets
    With Application.FindFormat.Font
        .FontStyle = "Bold"
        .Subscript = False
        .TintAndShade = 0
    End With
    With Sht
        For X = 1 To 10000
            Set delRow = .Cells.Find(What:="Total", _
                After:=.Range("A1"), _
                LookAt:=xlPart, _
                LookIn:=xlFormulas, _
                SearchOrder:=xlByRows, _
                SearchDirection:=xlPrevious, _
                MatchCase:=False, _
                SearchFormat:=True)
           If Not delRow Is Nothing Then 
               delRow.EntireRow.Delete Shift:=xlUp
           End If
        Next X
    End With
Next Sht
End Sub

答案 1 :(得分:1)

For Each ws In ActiveWorkbook.Worksheets
....
Next ws