使用Excel宏更改Excel列背景颜色

时间:2017-06-29 14:00:11

标签: excel excel-vba vba

对于一个越来越大的Excel文档,互联网我试图摆脱自动布局,因为它们会严重减慢我们的excel,使其无法使用。

我尝试创建一个宏,根据活动单元格值为单元格的背景着色。

  Sub find()

 Dim CurValue  As String
 Dim ColorIndex As String
 Dim Findr     As Range
 Dim MyRange As Range

 Set MyRange = ActiveCell
 CurValue = ActiveCell.Value

 With ActiveCell
    Set Findr = Range("A1:A10").find(CurValue)
    If Not Findr Is Nothing Then
        ColorIndex = Findr.Offset(ColumnOffset:=1).Value
        MyRange.Interior.ColorIndex = ColorIndex
'        rngStart.Select
    End If
 End With

End Sub

这个子工作完美。

然而对于这个问题: 现在我想在单元格更改时调用它,但是如果我在Sheet中单元格发生变化时调用宏。我尝试使用表单源代码进行每次更改。 但是它然后使用用户在更改之后跳转到的单元格而不是之前编辑的单元格。

如何让这个宏调用每个已更改的单元格,而不是新的选择单元格?

1 个答案:

答案 0 :(得分:0)

将以下内容放在相应的Worksheet对象中应该有效:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim CurValue  As String
Dim ColorIndex As String
Dim Findr     As Range
For Each AC In Target.Cells
    CurValue = AC.Value
    Set Findr = Range("A1:A10").find(CurValue)
    If Not Findr Is Nothing Then
        ColorIndex = Findr.Offset(ColumnOffset:=1).Value
        AC.Interior.ColorIndex = ColorIndex
    End If
Next
End Sub

注意 - A1:A10中的一个需要为空白,但空白旁边的B中的值必须具有 ColorIndex 值且不能为空。我建议用零清空电池中的所有颜色,但我看不出你的表格是什么空的'细胞看起来像..

For..Each循环用于处理一次更改多个单元格的位置,它会对每个更改的单元格执行颜色更改。

此外,细胞会改变'由于公式更改而不是编辑的结果,使用此方法不会更改。

相关问题