【问题标题】:Excel - VBA: Change the text color of a cell based on the text color of an adjecent cellExcel - VBA:根据相邻单元格的文本颜色更改单元格的文本颜色
【发布时间】:2013-10-18 08:08:43
【问题描述】:

我正在研究一个宏,它循环遍历范围 dData 并识别哪些单元格具有白色字体颜色。然后它会更改与 dData 白色相邻的任何单元格的字体颜色。下面的代码是我到目前为止所拥有的。它还不起作用,但是,我在正确的轨道上吗?

谢谢!

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim dData As Range
Dim Cell As Range

Set dData = Sheets("Sheet1").Range("l2:l10000")

For Each Cell In dData
    If Cell.Font.Color = 2 Then
        Cell.Offset(0, -1).Font.Color = 2
    End If
Next Cell
End Sub

【问题讨论】:

  • 不过,我认为您不想将此代码放入 SelectionChange 事件中。
  • 我有一个组合框可以触发另一个宏,我可以把它放在那里。关于目前为什么这不起作用的任何想法?
  • 您是遇到错误还是只是在运行时没有任何反应?
  • 我运行它时没有任何反应。
  • 此代码会影响Sheet1,无论您将其放置在哪个工作表模块中。您确定要检查Sheet1 的更改吗?

标签: vba colors fonts


【解决方案1】:

这似乎对我有用。

Sub Test()
Dim dData As Range
Dim Cell As Range

Set dData = Sheets("Sheet1").Range("l2:l10000")

For Each Cell In dData.Cells
        If Cell.Font.Color = 16777215 Then
            Cell.offset(,1).Font.Color = 16777215
        End If
Next
End Sub

注意另外dData的范围仅限于Sheet1

在我的电脑上,“白色”是一个长值 16777215,它适用于 2010 年的 Excel,我认为应该适用于 2007 年。在 Excel 2003 中我不确定。

试试这个

Sub Sample()
    Dim dData As Range, aCell As Range

    Set dData = Sheets("Sheet1").Range("L2:L10000")

    For Each aCell In dData.Cells
        If aCell.Font.ColorIndex = 2 Then _
        aCell.Offset(, 1).Font.ColorIndex = 2
    Next
End Sub

【讨论】:

  • 感谢您的帮助,但它似乎没有做任何事情。我要做的是测试“L”列中的哪些单元格具有白色字体,然后将字体颜色离子列“M”更改为白色。
  • @user1437463:如果你想改变 Col M 的颜色,那么为什么要 Offset(0,-1) ;) 试试 Offset(,1)
  • @david: you will need an extra If statement otherwise cells in Column A will raise an error. 为什么会这样?
  • @David:我不想发布另一个答案,所以我要编辑你的帖子。希望你不介意
  • @DavidZemens “A1”从何而来?我们在 Col L 中循环单元格;)
猜你喜欢
  • 2016-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多