我希望在工作簿中的每个工作表上都有一些工作表,跳过第一个工作表并进行一些格式化,但我希望这个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
答案 0 :(得分:1)
试试这个:
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
答案 1 :(得分:1)
您的代码很好,您只缺少一行,检查当前工作表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
答案 2 :(得分:1)
你几乎就在那里,因为你只错过了工作表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
语句:虽然在这种情况下它不会显着影响性能,但从纯粹的编码观点
答案 3 :(得分:0)
像这样遍历你的工作表,并检查索引属性(存储工作表位置),以确保它不是第一个。
Public Sub test()
For Each ws In Worksheets
If ws.Index > 1 Then
'Formatting goes here
End If
Next
End Sub