How to run the same code on all the worksheets in an Excel file

孤者浪人 提交于 2019-12-11 14:08:30

问题


I want to execute the following VBA code for each worksheet at once in an Excel file:

Sub sample_code()    
    Columns("B:B").Select
    Selection.Replace What:=" ", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
    Range("A:A,D:J").Select
    Range("D1").Activate
    Selection.Delete Shift:=xlToLeft
    Columns("F:P").Select
    Selection.Delete Shift:=xlToLeft
    Columns("A:E").EntireColumn.AutoFit
    Columns("B:B").ColumnWidth = 30.86
    Range("A1:E1").Select
    Selection.Font.Bold = True
End Sub

How can I do that?


回答1:


Like this:

Sub sample_code()
    Dim ws As Worksheet

    For Each ws In Worksheets
        With ws
            .Columns("B:B").Replace What:=" ", Replacement:="", LookAt:=xlPart, _
                SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
                ReplaceFormat:=False
            .Range("A:A,D:J").Delete Shift:=xlToLeft
            .Columns("F:P").Delete Shift:=xlToLeft
            .Columns("A:E").EntireColumn.AutoFit
            .Columns("B:B").ColumnWidth = 30.86
            .Range("A1:E1").Font.Bold = True
        End With
    Next ws
End Sub



回答2:


Also, add Application.ScreenUpdating = False to the beginning and Application.ScreenUpdating = True at the end to make this go much faster.



来源:https://stackoverflow.com/questions/12952194/how-to-run-the-same-code-on-all-the-worksheets-in-an-excel-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!