Creating a color vector in VBA

I want to check data tables over several years to find specially colored cells.

People have not always chosen the same color of cells for many years (they can all be the same for the human eye, but have different RGB values).

If I have a cell with an RGB interior color (255,23,50), is there a way to create a color vector to see if the color of the inside of the cell falls on it? I am trying to create a vector with +/- 15 RGB dots, so if I look for cells with RGB (255,23,50), I want a vector between RGB (255,38,65) and RGB (240,8, 35).

I could use the IF statement to see if the color is between these two values, but I could use the color vector for more applications (and the code would be easier to change if it needed to be changed).

This is if the expression works:

If ActiveWorkbook.Worksheets("Sheet1").Range("e5").Interior.Color >= RGB(240, 8, 35) And ActiveWorkbook.Worksheets("Sheet1").Range("e5").Interior.Color <= RGB(255, 38, 65) Then
    MsgBox ("yes")
Else
    MsgBox ("no")
End If

I am looking for something more like:

dim redVector as long ' or other appropriate variable type

' ***** code that defines the red vector *****

if range("e5").interior.color = redVector then
    ' do stuff
end if
+4
source share
1 answer

This should do:

Function IsInVector(srcColor, newColor, lOffset As Long) As Boolean

    Dim lSrcColor As Long
    Dim lNewColor As Long
    Dim lTemp     As Long

    lSrcColor = CLng(srcColor)
    lNewColor = CLng(newColor)

    lTemp = (lSrcColor - lNewColor) / 65536
    lTemp = Abs(Round(lTemp, 0))

    If lOffset <> lTemp Then
        IsInVector = False
    Else
        IsInVector = True
    End If

End Function

'/ Example usage::::  
Sub test()

    Debug.Print IsInVector(RGB(255, 23, 50), RGB(255, 38, 65), 15) '~~~> True
    Debug.Print IsInVector(RGB(255, 23, 50), RGB(255, 43, 63), 15) '~~~> False
    Debug.Print IsInVector(RGB(255, 23, 50), RGB(255, 38, 65), 15) '~~~> True

End Sub
+1
source

Source: https://habr.com/ru/post/1667017/


All Articles