VBA-循环以在一些工作表中标准化标头,但省略了一些

时间:2019-06-26 20:24:42

标签: excel vba

我试图遍历工作簿中的13个工作表中的11个,以标准化一些列标题。运行宏时,它只会在当前活动的工作表上进行更改。

我尝试过在if语句中添加要省略的工作表名称。这就是我所拥有的

Sub Set_Headings()
    Dim ws As Worksheet
    'loop through each sheet in the workbook except for "Main" and "Overall" and standardize column headers'
    For Each ws In ThisWorkbook.Worksheets
        If ws.Name <> "Main" And ws.Name <> "Overall" Then
            Range("B2").Value = "Active / Days Off / Holidays/ Training / MOD / LOA"
            Range("E2").Value = "Active / Days Off / Holidays/ Training / MOD / LOA"
            Range("H2").Value = "Active / Days Off / Holidays/ Training / MOD / LOA"
            Range("K2").Value = "Active / Days Off / Holidays/ Training / MOD / LOA"
            Range("C2").Value = "Unit / Notes"
            Range("F2").Value = "Unit / Notes"
            Range("I2").Value = "Unit / Notes"
            Range("L2").Value = "Unit / Notes"
            Range("G2").Value = "Drivers"
        End If
    Next ws
End Sub

我希望将这些标题应用于除“主要”和“总体”之外的所有工作表,但它仅将更改应用于当前活动的工作表。

1 个答案:

答案 0 :(得分:0)

默认情况下,如果您未明确声明要与Range一起使用的工作表,则它将默认为当前的ActiveSheet

使用其中一行的示例为ws.Range("L2").Value = "Unit / Notes"

如@BruceWayne所述,使用With语句将消除重复的限定表达式,从而使您的代码更具可读性。

Sub Set_Headings()
    'loop through each sheet in the workbook except for "Main" and "Overall" and standardize column headers'
    Dim ws As Worksheet
    For Each ws In ThisWorkbook.Worksheets
        With ws
            If .Name <> "Main" And .Name <> "Overall" Then
                .Range("B2").Value = "Active / Days Off / Holidays/ Training / MOD / LOA"
                .Range("E2").Value = "Active / Days Off / Holidays/ Training / MOD / LOA"
                .Range("H2").Value = "Active / Days Off / Holidays/ Training / MOD / LOA"
                .Range("K2").Value = "Active / Days Off / Holidays/ Training / MOD / LOA"
                .Range("C2").Value = "Unit / Notes"
                .Range("F2").Value = "Unit / Notes"
                .Range("I2").Value = "Unit / Notes"
                .Range("L2").Value = "Unit / Notes"
                .Range("G2").Value = "Drivers"
            End If
        End With
    Next ws
End Sub