在Excel中基于单元格颜色返回细胞索引
我试图比较一个单元格的颜色和范围的颜色,并返回该颜色匹配在Excel中该单元格的相应的列索引。
MatchColour
我想出了下面的vba代码,但它不工作。
Function MATCHCOLOUR(rColor As Range, rRange As Range) As Long Dim lCol As Long Dim vResult As Long lCol = rColor.Interior.Color If rRange.Interior.Color = lCol Then vResult = rRange.ColumnIndex End If MATCHCOLOUR = vResult End Function
示例结果: MATCHCOLOUR(A1,B1:B10)
应该返回5(即columnindex),其中A1和B5的颜色匹配。
我不确定你想从UDF中获得什么参数,所以我的代码包含了其中的一些。
首先,你需要遍历你的Range.Cells
,在我的代码中,一旦出现匹配,就读取Cell的Column
(或Row
)并Exit
For
循环。
其次,可以得到一些可能的结果,让我们使用你的样品结果MATCHCOLOUR(A1,B1:B10)
,并且单元格B5具有与单元格A1相同的颜色:
Abosulte Column :B5的列号>> retruns 2
相对列 :A1的相对列数为A1返回1
绝对行 :B5的行数回退5
相对行 :B5的相对行号A1 >>返回4
码
Function MATCHCOLOUR(rColor As Range, rRange As Range) As Long Dim vResult As Long Dim c As Range For Each c In rRange.Cells If c.Interior.Color = rColor.Interior.Color Then ' getting the absolute column number of the match in the Range vResult = c.Column ' getting the absolute column number of the match in the Range vResult = c.Row ' getting the relative columns number of the match in the Range and current cell vResult = c.Column - rColor.Column ' getting the relative rows number of the match in the Range and current cell vResult = c.Row - rColor.Row Exit For End If Next c MATCHCOLOUR = vResult End Function
所以,运行这个函数,当试图获得第一次出现的绝对行的单元格颜色匹配时,单元格B5 >>将返回5:
也许你可以尝试遍历单元格的范围,并返回该范围内的计数。 这有点暴躁,但应该涵盖你所需要的:
Function MATCHCOLOUR(rColor As Range, rRange As Range) As Long Dim lCol As Long Dim vResult As Long Dim vFound As Long lCol = rColor.Interior.Color vResult = 0 vFound = 0 For Each rCell In rRange.Cells vResult = vResult + 1 If rCell.Interior.Color = lCol Then vFound = 1 Exit For End If Next If vFound = 0 Then MATCHCOLOUR = 0 Else MATCHCOLOUR = vResult End If End Function