我正在尝试将单元格的颜色与范围的颜色进行比较,并返回颜色在excel中匹配的范围内的单元格的相应Column-Index。
匹配颜色
我想出了下面的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的颜色匹配。
答案 0 :(得分:2)
我不确定您尝试从UDF返回的参数是什么,因此下面的代码中包含了一些参数。
首先,您需要循环浏览Range.Cells
,在我的代码中,我假设一旦匹配,您就会读到Cell Column
(或Row
)和Exit
循环For
。
其次,您可以获得一些可能的结果,让我们使用您的样本结果MATCHCOLOUR(A1,B1:B10)
,而单元格B5具有相同颜色的单元格A1:
Abosulte Column :B5的列号>>重演2
相对列 :B%与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&gt;&gt;将返回5:
答案 1 :(得分:0)
也许你可以尝试逐个细胞遍历范围并返回该范围内的计数。这有点蛮力,但应该涵盖你需要的东西:
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