在所有工作表上运行脚本excel

时间:2015-03-20 06:50:16

标签: excel vba excel-vba

我有这个脚本搜索已定义的字符串并在找到它时删除该列。我想在工作簿中的所有工作表上运行相同的搜索。到目前为止,我已经尝试过像这样设置它。但它只会在活动表上运行。

Sub RunMacroOnAllSheetsToRight()
For i = ActiveSheet.Index To Sheets.Count
    Call MyFunction(i)
Next i
End Sub


Function MyFunction(i)
Dim c As Range
            Dim str As String

            str = "SearchStringHere"

            For Each c In ActiveSheet.UsedRange
               If InStr(c.Value, str) > 0 Then
               c.EntireColumn.Delete Shift:=xlToLeft
               End If
            Next c

End Function

脚本现在循环,但由于某种原因只删除单个列。需要能够匹配和删除每张纸的多个列。

1 个答案:

答案 0 :(得分:1)

您只需要在“功能”中更改ActiveSheet,它就会更好!

顺便说一句:你可以有一个带参数的Sub(如下所示),只有当你有输出结果时才需要一个函数(在你的例子中没有)。

2个主要变化: - 添加Set Ws = Nothing以释放Ws - 更改了逐列的增量,因为当删除列越来越多时,您将错过分析下一列(j + 1),现在是列(j)

Sub RunMacroOnAllSheetsToRight()
Application.ScreenUpdating = False
For i = ActiveSheet.Index To Sheets.Count
    Column_Delete i, "SearchStringHere"
Next i
Application.ScreenUpdating = True
End Sub


Sub Column_Delete(ByVal Sheets_Index As Integer, ByVal Str_to_Find As String)

Dim Ws As Worksheet
Set Ws = Worksheets(Sheets_Index)


Dim EndColumn As Integer
EndColumn = Ws.Cells(1, Columns.Count).End(xlToLeft).Column

'descending travel of the columns as we are going to delete some of them
For j = 1 To EndColumn
    If InStr(Ws.Cells(1, EndColumn - j + 1), Str_to_Find) > 0 Then
        Ws.Columns(EndColumn - j + 1).EntireColumn.Delete Shift:=xlToLeft
    End If
Next j

'Don't forget to free Ws (like I did...)
Set Ws = Nothing

End Sub