跳过VBA中工作簿的第一个工作表

我想在工作簿中的每个工作表上都有一些工作表,并跳过第一个工作表,然后做一些格式化工作,但是我希望这个vba代码跳过第一个工作表(名字可以不同但始终是第一个)。 所以问题是我该怎么做呢?

Sub ex2() Dim kl As Worksheet Dim Ws_Count As Integer Dim a As Integer Ws_Count = ActiveWorkbook.Worksheets.Count For a = 2 To Ws_Count With Rows("2:2") .RowHeight = 20 .Interior.Color = RGB(150, 250, 230) End With With Range("B2") .Value = "Sheet Number" & " " & a .Font.Size = 12 .Font.Bold = True .Font.Underline = True End With Next a End Sub 

你的代码是好的,你只是错过了一行,检查当前表kl.Index

 Option Explicit Sub ex2() Dim kl As Worksheet For Each kl In Worksheets ' not the first worksheet If kl.Index > 1 Then With kl.rows("2:2") .RowHeight = 20 .Interior.Color = RGB(150, 250, 230) End With With kl.Range("B2") .Value = "Sheet Number" & " " & kl.Index - 1 .Font.Size = 12 .Font.Bold = True .Font.Underline = True End With End If Next kl End Sub 

尝试这个:

 Sub ex2() Dim Ws_Count As Integer Dim a As Integer Ws_Count = ActiveWorkbook.Worksheets.Count For a = 2 To Ws_Count With Worksheets(a) 'rest of your code End With Next a End Sub 

使用发布的代码,最终的结果是:

 Sub ex2() Dim Ws_Count As Integer Dim a As Integer Ws_Count = ActiveWorkbook.Worksheets.Count For a = 2 To Ws_Count With Worksheets(a) Worksheets(a).Activate With Rows("2:2") .RowHeight = 20 .Interior.Color = RGB(150, 250, 230) End With With Range("B2") .Value = "Sheet Number" & " " & worksheets(a).Index - 1 .Font.Size = 12 .Font.Bold = True .Font.Underline = True End With Next a End Sub 

你几乎在那里,因为你只是错过了工作表specification

你可以添加一个或者添加一个Worksheets(a).Activate语句在For a = 2 To Ws_Count或者更好的方法是将你的格式化代码包含在With Worksheets(a) ... End With块,添加每个range参考之前的点( . ),并使它们参考当前引用的工作表,如下所示

 Sub ex2() Dim a As Integer For a = 2 To Worksheets.Count With Worksheets(a) '<--| reference current index worksheet With .Rows("2:2") '<--| reference current worksheet row 2 .RowHeight = 20 .Interior.Color = RGB(150, 250, 230) End With With .Range("B2") '<--| reference current worksheet cell "B2" .Value = "Sheet Number" & " " & a .Font.Size = 12 .Font.Bold = True .Font.Underline = True End With End With Next a End Sub 

因此,不需要任何只能使用一次的If语句:尽pipe在这种情况下它不会显着影响性能,但从纯粹的编码angular度来看,效率会非常低

像这样遍历你的工作表,并检查索引属性(它存储工作表的位置),以确保它不是第一个。

 Public Sub test() For Each ws In Worksheets If ws.Index > 1 Then 'Formatting goes here End If Next End Sub