我写了一个代码来改变每张纸的某些单元格的颜色格式(我有12张相似的纸张[Sheets(1)-Sheets(12)];以及摘要表(Sheets(13))。
当我运行它时,我打算在Sheets(13)上执行的代码正在Sheets(12)中执行。当然我可以将代码分开,并专门执行第13页的代码,但我想了解它为什么不起作用。
Sub forEachWs()
Dim x As Long
Dim ws As Sheets
For x = 1 To 12
ThisWorkbook.Sheets(x).Activate
Call changecolormonths
Range("A2").Select
Next x
If x = 13 Then
Call changesummarycolor 'this is the code that is wrongly executed at sheet 12
End If
End Sub
答案 0 :(得分:0)
您应该明确编码。避免使用Select
和ActiveWorksheet
。如果没有在前面说明纸张(您希望使用特定范围),请不要参考范围。不允许VBA为您做出假设,但告诉VBA您想要什么。具体。
这是用显式引用重写的代码。这应该可以解决你的问题。
Option Explicit
Sub forEachWs()
Dim ws As Worksheet
Dim wsSUM As Worksheet
Dim bolfound As Boolean
bolfound = False
For Each wsSUM In ThisWorkbook.Worksheets
If wsSUM.Name = "Summary" Then
bolfound = True
Exit For
End If
Next wsSUM
If bolfound = False Then
MsgBox "Couldn't find the summary sheet." & Chr(10) & "Aborting..."
Exit Sub
End If
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> wsSUM.Name Then
Call changecolormonths(ws, wsSUM)
ws.Activate
ws.Range("A2").Select
Else
Call changesummarycolor(wsSUM)
End If
Next ws
End Sub
'below code are meant for Sheets(1) to Sheets(12)
Sub changecolormonths(ws As Worksheet, wsSUM As Worksheet)
Dim headercolor As Long
Dim proccolor As Long
headercolor = wsSUM.Range("B24").Value
proccolor = wsSUM.Range("B25").Value
With ws
.Range("A1:H1,L8:M8,K16:M16,L32:N32,L40:N40").Interior.Pattern = xlSolid 'header,total color
.Range("A1:H1,L8:M8,K16:M16,L32:N32,L40:N40").Interior.ColorIndex = headercolor
.Range("A1:H1,L8:M8,K16:M16,L32:N32,L40:N40").Font.ColorIndex = 2
.Range("K9:K15,K33:K39").Interior.Pattern = xlSolid 'procedure
.Range("K9:K15,K33:K39").Interior.ColorIndex = proccolor
End With
End Sub
'below code are meant for Sheets(13)
Sub changesummarycolor(wsSUM As Worksheet)
Dim headercolor As Long
Dim proccolor As Long
With wsSUM
headercolor = .Range("B24").Value
proccolor = .Range("B25").Value
.Range("B4:N4 , A12: N12 , N5: N11").Interior.Pattern = xlSolid 'summary header,total color
.Range("B4:N4 , A12: N12 , N5: N11").Interior.ColorIndex = headercolor
.Range("B4: N4 , A12: N12 , N5: N11").Font.ColorIndex = 2 'summary procedure
.Range("A5:A11").Interior.Pattern = xlSolid
.Range("A5:A11").Interior.ColorIndex = proccolor
End With
End Sub
请注意,我没有您的Excel文件,因此无法测试上述代码。我只是把它改写成了我的头脑。因此,它可能需要一些调整。然而,变化很小,我相信它应该按预期运行。不过,请随时告诉我是否有任何问题。 :)子>