用户定义的函数,用于更改单元格的颜色

时间:2015-05-29 21:08:47

标签: excel vba excel-vba

我看到许多用户在尝试使用用户定义的函数更改单元格颜色时提出问题。我总是认为不可能这样做。我的理解是,除了包含公式的单元格的值之外,用户定义的函数不能更改单元格的任何属性。 Subs是改变细胞本身的东西。

但是,在玩一些代码来测试时,我发现情况并非总是如此。
使用简单的代码:

Function ColorCell(rng As Range)
If rng.Value = 1 Then
   ColorCell = False
Else
   ColorCell = True
   rng.Interior.ColorIndex = 3
End If
End Function

如果我将函数输入单元格,我会达到预期的结果,没有单元格会改变颜色。但是,如果我使用公式>插入功能按钮并导航到我的公式,以这种方式插入, 为目标单元格着色 Cell Color Function

这怎么可能,为什么在以不同方式输入时功能表现不同?

编辑:这是使用Excel 2007测试的

4 个答案:

答案 0 :(得分:4)

使用此代码...只需替换工作表名称并尝试

Sheets("sheet_name").range(j:j).clear

for j=2 to 15
if Sheets("sheet_name").Cells(j, 1).value=1 then

else

Sheets("sheet_name").Cells(j, 1).Interior.ColorIndex = 3
next j

答案 1 :(得分:0)

我使用Worksheet_Change事件来检测工作范围内的值变化。例子。我希望在范围A1:A5改变时做一些事情。我在下面的活动中使用。

Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range(<Your working range>)) Is Nothing Then 'Define range that you want to do
       'Statement here
       ...

    End If
End Sub

当范围值发生变化时。它将执行您的代码。

和其他方式。使用条件格式。

答案 2 :(得分:0)

我们都迟早会发现,在用户功能中,您无法访问直接更改电子表格中内容的附件。

但试试这个:

Dim ColorMeTarget As Range, ColorMeVal As Long

Public Function ColorMe(ByVal TargetRange As Range, ByVal ColVal As Long)
  Set ColorMeTarget = TargetRange
  ColorMeVal = ColVal
  ColorMe = ColVal
End Function

Public Sub ColorMeSub()
  Application.OnTime Now + TimeValue("00:00:05"), "ColorMeSub"
  If ColorMeTarget.Interior.Color <> ColorMeVal Then ColorMeTarget.Interior.Color = ColorMeVal
End Sub

如果先运行sub,它将不断扫描静态变量ColorMeTarget和ColorMeVal以查看是否有变化。 ColorMe函数将设置这些值。如果ColorMeTarget尚未初始化,则需要一些额外的代码。

如果你变得更聪明,你可以先让函数检查是否确实有变化并将新的着色请求添加到堆栈中。然后,你的重复发生的子可以“赶上”,特别是如果你有很多这样的功能。

然后你甚至可以在你的功能/宏中添加各种附加控件 - 即使是最新版本的'条件制作'也不会覆盖! YAY !!!!

要尝试的东西:在我的一些自动化宏中,我可以通过一个函数设置OnTime但不能在这里工作。让函数设置OnTime并且没有需要初始化的reoccuring子会更清晰。

答案 3 :(得分:0)

还可以尝试基于单元格条件(也就是条件格式)自动着色单元格的非脚本方法:

highlight desired range & click "conditional formatting from the toolbar

use either an established rule or make a new rule

note options on rule types; I selected one to simply format the range based on cell contents.  You can format based on a formula as well. Set the conditions to test ... in this case I said the condition is when a cell value is more than 5.  Then click on format and set the desire format whether it be a font change or shading of the cell, etc. Here I selected to shade the cell a color of green when above 5 Here is the result.  You can delete the contents of the cells without deleting the conditional formatting set for the cells.