Excel功能 - 根据另一个单元格选择设置单元格颜色

时间:2018-04-26 13:21:12

标签: excel vba function

我需要编写一个函数,根据另一行中单元格的颜色,在一行中为一堆单元格着色。我尝试了一些不同的VBA变体,但这就是我想要做的事情:

Public Function CopyColorFormat(Target As Range)

    If Not Target.Interior.Color Is Nothing Then

        ActiveCell.Interior.ThemeColor = Target.Interior.ThemeColor

    End If

End Function

然后我去了A1并将公式设置为= CopyColorFormat(C1)。 (C1是紫色,我希望A1也是紫色阴影。)但是,这会导致#VALUE!我尝试将函数放入单元格中的错误。

我想要这个并且不使用条件格式的原因是我需要将它应用于 ton 的单元格(通过它们相应的单元格)并且不想为每个单元格制定规则

1 个答案:

答案 0 :(得分:1)

我对功能知之甚少,但是这个宏应该可以帮到你。

Sub color_cells()
Application.ScreenUpdating = False

Dim currentcell As Range
Dim copycell As Range
Dim current As Long
Dim copy As Long

Set currentcell = Range("A1")
Set copycell = Range("C1")
current = 1
copy = 1

For x = 1 To 8 ' instead of 8 - enter the number of rows you want the code to run on.
    If Not copycell.Interior.ColorIndex = xlNone Then

    copycell.copy
    currentcell.PasteSpecial xlPasteFormats

    End If

    current = current + 1
    copy = copy + 1

    Set currentcell = Range("A" & current)
    Set copycell = Range("C" & copy)
Next x

Application.ScreenUpdating = True
End Sub

如果您同时使用多个工作簿,则可能需要指定运行代码的工作簿和工作表。