簡體   English   中英

在Excel中根據單元格顏色返回單元格索引

[英]Returning Cell Index based on Cell Color in 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欄 :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 >>將返回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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM