Consulting

Results 1 to 4 of 4

Thread: Copy color from range of cells

  1. #1
    VBAX Newbie
    Joined
    Nov 2016
    Posts
    3
    Location

    Copy color from range of cells

    I'm trying to copy color from cell to cell (not actually range) but it does not work, I always get #VALUE error.
    This is my code, it's self-explanatory (the idea is to copy background color, content can be set as blank):

    Public Function colorBG(src As Range) As String
        ActiveCell.Interior.ColorIndex = src.Interior.ColorIndex
        colorBG = ""
    End Function
    I've even tried using source and destination (dest.Interior.ColorIndex = src.Interior.ColorIndex) but it doesn't work.

    Any ideas what am I doing wrong? :-/

  2. #2
    VBAX Expert
    Joined
    Sep 2016
    Posts
    788
    Location
    Option Explicit
    
    Sub test()
        Dim r As Range
        
        Set r = Range("a1")
        
        Range("b1").Interior.ColorIndex = colorBG(r)
        Range("c1").Interior.ColorIndex = colorBG(r)
        
    End Sub
    
    
    Private Function colorBG(src As Range) As Integer
        colorBG = src.Interior.ColorIndex
    End Function

  3. #3
    VBAX Newbie
    Joined
    Nov 2016
    Posts
    3
    Location
    thanks,

    but I don't quite understand it...
    As far as I can see, colorBG() retrieves color code and returns it. And test() changes BG of fixed cells (not the ActiveCell) - and it's not even called from within colorBG().

    Or am I missing something? :-$




    Quote Originally Posted by mana View Post
    Option Explicit
    
    Sub test()
        Dim r As Range
        
        Set r = Range("a1")
        
        Range("b1").Interior.ColorIndex = colorBG(r)
        Range("c1").Interior.ColorIndex = colorBG(r)
        
    End Sub
    
    
    Private Function colorBG(src As Range) As Integer
        colorBG = src.Interior.ColorIndex
    End Function

  4. #4
    VBAX Newbie
    Joined
    Nov 2016
    Posts
    3
    Location
    Answering myself, it is actually quite simple when you dismiss the idea of using function in any cell.

    I defined a sub that is called every time there is change of selection (=moving around cells) on the current sheet.

    As the source and destination columns are known, I used a loop to iterate through all the lines in them.
    Instead of "ColorIndex" I used "Color" (that makes the exact copy of color and not the nearest one of 56 Excel colors).

    If anyone needs it, here's the code (put under "SheetX" in VBA):

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        For line = 1 To 999
            Range("I" & line).Interior.Color = Range("A" & line).Interior.Color
        Next line
    End Sub

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •