Excel宏指定工作表颜色修改问题:切换工作表时误改活动表
问题原因
你的代码里,Range(Cells(c.Row, 1), Cells(c.Row, 5))没有明确指定所属工作表,VBA会默认使用当前活动工作表执行颜色修改,这就是切换到其他工作表时出错的核心原因。虽然你写了With ThisWorkbook.Worksheets("fivemin"),但没通过.把Range/Cells和这个With对象绑定,相当于白写了这个With块。
修改后的代码(两种可选写法)
写法一:统一用变量指定工作表
Private Sub COLOR() Application.ScreenUpdating = False Dim ws As Worksheet Set ws = ThisWorkbook.Worksheets("FIVEMIN") '绑定目标工作表 Dim c As Variant For Each c In ws.Range("E6:E11").Cells '所有操作前加ws.,强制指向fivemin工作表 If c.Value < 0 Then ws.Range(ws.Cells(c.Row, 1), ws.Cells(c.Row, 5)).Interior.ColorIndex = 22 Else ws.Range(ws.Cells(c.Row, 1), ws.Cells(c.Row, 5)).Interior.ColorIndex = 35 End If Next c Application.ScreenUpdating = True '恢复屏幕刷新 End Sub
写法二:用With块简化代码
Private Sub COLOR() Application.ScreenUpdating = False Dim ws As Worksheet Set ws = ThisWorkbook.Worksheets("FIVEMIN") Dim c As Variant With ws '绑定目标工作表到With块 For Each c In .Range("E6:E11").Cells '所有Range/Cells前加.,代表当前With块的工作表 If c.Value < 0 Then .Range(.Cells(c.Row, 1), .Cells(c.Row, 5)).Interior.ColorIndex = 22 Else .Range(.Cells(c.Row, 1), .Cells(c.Row, 5)).Interior.ColorIndex = 35 End If Next c End With Application.ScreenUpdating = True End Sub
关键改动说明
- 所有
Range和Cells前必须加上工作表标识(ws.或.),强制指定操作对象为fivemin工作表,彻底和活动工作表解绑。 - 补充了
Application.ScreenUpdating = True,宏结束后恢复屏幕刷新,避免Excel界面卡顿。
内容的提问来源于stack exchange,提问作者cjb3
相关产品推荐
相关产品推荐

