VBA 遍历A5:A219设置单元格背景色时如何同步给对应B列设同色
解决方案
核心是通过当前遍历的A列单元格定位同行的B列单元格,有两种简便的定位写法:
- 用
Offset偏移方法:companyCol.Offset(0, 1)表示与当前单元格同行、向右偏移1列的B列单元格 - 用行号直接定位:
wsLookup.Cells(companyCol.Row, "B")直接指定行号和列名定位对应单元格
推荐优化后代码(逻辑更简洁,避免重复赋值)
Dim companyCol As Range Dim fillColorIndex As Integer ' 存储当前行需要填充的色号 For Each companyCol In wsLookup.Range("A5:A219") ' 判定单元格值匹配对应色号 Select Case companyCol.Value Case "16247773": fillColorIndex = 20 Case "49407": fillColorIndex = 44 Case "16724889": fillColorIndex = 17 Case Else: fillColorIndex = -4142 ' 无填充色 End Select ' 同时给A、B列同位置单元格设置背景色 companyCol.Interior.ColorIndex = fillColorIndex companyCol.Offset(0, 1).Interior.ColorIndex = fillColorIndex Next companyCol
不修改原有If结构的修改方案
直接在每个判断分支中新增一行设置B列颜色即可,示例:
Dim companyCol As Range For Each companyCol In wsLookup.Range("A5:A219") If companyCol.Value = "16247773" Then companyCol.Interior.ColorIndex = 20 companyCol.Offset(0,1).Interior.ColorIndex = 20 ' 新增行,设置同行B列颜色 ElseIf companyCol.Value = "49407" Then companyCol.Interior.ColorIndex = 44 companyCol.Offset(0,1).Interior.ColorIndex = 44 ' 新增行,设置同行B列颜色 ElseIf companyCol.Value = "16724889" Then companyCol.Interior.ColorIndex = 17 companyCol.Offset(0,1).Interior.ColorIndex = 17 ' 新增行,设置同行B列颜色 Else companyCol.Interior.ColorIndex = -4142 companyCol.Offset(0,1).Interior.ColorIndex = -4142 ' 新增行,设置同行B列颜色 End If Next companyCol
内容的提问来源于stack exchange,提问作者Andrew D
相关产品推荐
相关产品推荐

