基于颜色的返回范围

我试图在Excel中写一个UDF迭代一个给定的范围,在该范围内寻找给定背景颜色的单元格,然后返回一个包含该背景颜色的单元格范围。 我对VBA非常陌生,我不确定我是否正确地使用Googlesearch来find我要找的内容。 这是我迄今为止给出的代码。

Function findRed(MyRange As Range) As Variant Dim redRange As Range Application.Volatile For Each cell In MyRange If cell.Interior.ColorIndex = 3 Then End If Next cell End Function 

我在网上发现了一个简单的函数,它可以返回包含背景颜色的单元格的计数,但是我不知道在IF语句中该怎么做。 find红色的细胞然后做什么? 以便返回实际上是红色的单元格的范围。

testing:

 Function findRed(MyRange As Range) As Range Dim redRange As Range, cell As Range Application.Volatile For Each cell In MyRange If cell.Interior.ColorIndex = 3 Then If redRange Is Nothing Then Set redRange = cell Else Set redRange = Application.Union(redRange, cell) End If End If Next cell Set findRed = redRange End Function 

编辑:如果你想检查返回的范围地址…

 Function findRedAddress(MyRange As Range) As String Application.Volatile On Error Resume Next findRedAddress = findRed(MyRange).Address(False, False) End Function 

取决于你需要做什么与find的范围? 例如:
MsgBox cell.Address将返回单元格的地址
MsgBox cell.value返回单元格的内容