Gass
Gass

Reputation: 9344

Is it possible to use a custom color to fill a cell using VBA?

I'm using the color index 20 to fill up some cells but it is not my preferred color for this project. I would use a custom light gray which is not in the color index palette. Is it possible?

This is my code:

Sheets("Panel").Range("E7:E31").Interior.ColorIndex = 20

Upvotes: 2

Views: 2492

Answers (3)

FaneDuru
FaneDuru

Reputation: 42236

Try the next code to choose the color you need. For RGB colors press Custom tab:

Sub testEditColorDialog()
 'Create variables for the color codes
 Dim FullColorCode As Long, RGBRed As Long, RGBGreen As Long, RGBBlue As Long

 'Get the color from the active cell (it can be any cell...):
 FullColorCode = ActiveCell.Interior.Color

 'Get the RGB value for each color (possible values 0 - 255)
 RGBRed = FullColorCode Mod 256
 RGBGreen = (FullColorCode \ 256) Mod 256
 RGBBlue = FullColorCode \ 65536

 'Open the ColorPicker dialog box for the active cell interior color
 If Application.Dialogs(xlDialogEditColor).Show _
               (1, RGBRed, RGBGreen, RGBBlue) = True Then
    'selected the DialogBox (the edited one):
    FullColorCode = ActiveWorkbook.Colors(1)
    
    'Set the chosen color back to the anlized cell:
    ActiveCell.Interior.Color = FullColorCode
 Else
    'nothing in case of Cancel
 End If
End Sub

I am not the creator of the above code. I only adapted something found on the internet, some time ago, to work according to my needs...

Upvotes: 2

braX
braX

Reputation: 11755

Here is the simplest way...

Range("A1").Interior.Color = RGB(192, 192, 192)

https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/rgb-function

You can get the RGB values any way you like. MS Paint has that ability using the eyedropper tool.

Upvotes: 1

VBasic2008
VBasic2008

Reputation: 54807

Cell Color Picker

  • You can apply the desired color to a cell and run the following program, select the cell and press ENTER or select OK and the color value is copied to the clipboard, waiting for you to use CTRL+V.

The Code

Option Explicit

Sub CellColorPicker()
    Dim rgAddress As String
    If TypeName(Selection) = "Range" Then
        rgAddress = Selection.Cells(1).Address
    Else
        rgAddress = "A1"
    End If
    Dim rg As Range
    On Error Resume Next
    Set rg = Application.InputBox("Pick a cell", "ColorPicker", _
        rgAddress, , , , , 8)
    On Error GoTo 0
    If Not rg Is Nothing Then
        With CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
            .SetText rg.Cells(1).Interior.Color
            .PutInClipboard
        End With
    End If
End Sub

Upvotes: 1

Related Questions