Ugrás a tartalomra

Hogyan lehet megváltoztatni az alak színét az Excel cellaértéke alapján?

Az alak színének megváltoztatása egy adott cellaérték alapján érdekes feladat lehet az Excelben, például, ha az A1 cellájának értéke 100-nál kisebb, akkor az alak színe piros, ha A1 nagyobb, mint 100 és kevesebb, mint 200, akkor a az alak színe sárga, és ha az A1 nagyobb, mint 200, akkor az alak színe zöld, az alábbi képernyőkép szerint. Az alak színének megváltoztatásához egy cellaérték alapján ez a cikk bemutatja a módszert az Ön számára.

doc az alak színének megváltoztatása 1

Változtassa meg az alak színét a cella értéke alapján, VBA kóddal


nyíl kék jobb buborék Változtassa meg az alak színét a cella értéke alapján, VBA kóddal

Az alábbi VBA-kód segíthet az alak színének megváltoztatásában egy cellaérték alapján, kérjük, tegye a következőket:

1. Kattintson a jobb gombbal a lapfülre, amelyen módosítani szeretné az alak színét, majd válassza ki Kód megtekintése a helyi menüből, a kiugrottban Microsoft Visual Basic for Applications ablakba, kérjük, másolja és illessze be a következő kódot az üresbe Modulok ablak.

VBA kód: Az alak színének módosítása a cella értéke alapján:

Private Sub Worksheet_Change(ByVal Target As Range)
'Updateby Extendoffice 20160704
    If Intersect(Target, Range("A1")) Is Nothing Then Exit Sub
    If IsNumeric(Target.Value) Then
        If Target.Value < 100 Then
            ActiveSheet.Shapes("Oval 1").Fill.ForeColor.RGB = vbRed
        ElseIf Target.Value >= 100 And Target.Value < 200 Then
            ActiveSheet.Shapes("Oval 1").Fill.ForeColor.RGB = vbYellow
        Else
            ActiveSheet.Shapes("Oval 1").Fill.ForeColor.RGB = vbGreen
        End If
    End If
End Sub

doc az alak színének megváltoztatása 2

2. Ezután, amikor beírja az értéket az A1 cellába, az alak színe megváltozik az Ön által megadott cellaértékkel.

Megjegyzések: A fenti kódban A1 az a cellaérték, amely alapján az alak színe megváltozna, és a 1. ovális a beillesztett alak alakjának neve, megváltoztathatja őket az Ön igényeinek megfelelően.

A legjobb irodai hatékonyságnövelő eszközök

🤖 Kutools AI Aide: Forradalmasítsa az adatelemzést a következők alapján: Intelligens végrehajtás   |  Kód létrehozása  |  Hozzon létre egyéni képleteket  |  Adatok elemzése és diagramok létrehozása  |  A Kutools funkciók meghívása...
Népszerű szolgáltatások: Ismétlődések keresése, kiemelése vagy azonosítása   |  Üres sorok törlése   |  Oszlopok vagy cellák kombinálása adatvesztés nélkül   |   Kerek Formula nélkül ...
Szuper keresés: Több kritérium VLookup    Többértékű VLookup  |   VLookup több munkalapon   |   Fuzzy Lookup ....
Speciális legördülő lista: Gyors legördülő lista létrehozása   |  Függő legördülő lista   |  Többszörösen válassza ki a legördülő listát ....
Oszlopkezelő: Adjon meg egy adott számú oszlopot  |  Oszlopok mozgatása  |  Kapcsolja be a Rejtett oszlopok láthatósági állapotát  |  Tartományok és oszlopok összehasonlítása ...
Kiemelt funkciók: Rács fókusz   |  Design nézet   |   Nagy Formula bár    Munkafüzet és lapkezelő   |  Erőforrás-könyvtár (Auto szöveg)   |  Dátumválasztó   |  Kombinálja a munkalapokat   |  Cellák titkosítása/dekódolása    E-mailek küldése listánként   |  Szuper szűrő   |   Speciális szűrő (félkövér/dőlt/áthúzott szűrés...) ...
A 15 legjobb eszközkészlet12 szöveg Eszközök (Szöveg hozzáadása, Karakterek eltávolítása,...)   |   50 + Táblázatos Típusai (Gantt-diagram,...)   |   40+ Praktikus képletek (Számolja ki az életkort a születésnap alapján,...)   |   19 beszúrás Eszközök (Helyezze be a QR-kódot, Kép beszúrása az útvonalból,...)   |   12 Átalakítás Eszközök (Számok szavakig, Valuta átváltás,...)   |   7 Egyesítés és felosztás Eszközök (Haladó kombinált sorok, Hasított sejtek,...)   |   ... és több

Töltsd fel Excel-készségeidet a Kutools for Excel segítségével, és tapasztald meg a még soha nem látott hatékonyságot. A Kutools for Excel több mint 300 speciális funkciót kínál a termelékenység fokozásához és az időmegtakarításhoz.  Kattintson ide, hogy megszerezze a leginkább szükséges funkciót...

Leírás


Az Office lap füles felületet hoz az Office-ba, és sokkal könnyebbé teszi a munkáját

  • Füles szerkesztés és olvasás engedélyezése Wordben, Excelben és PowerPointban, Publisher, Access, Visio és Project.
  • Több dokumentum megnyitása és létrehozása ugyanazon ablak új lapjain, mint új ablakokban.
  • 50% -kal növeli a termelékenységet, és naponta több száz kattintással csökkenti az egér kattintását!
Comments (21)
Rated 4 out of 5 · 1 ratings
This comment was minimized by the moderator on the site
Como faço para para variar as cores da forma se minha opções for em formato de texto, como "Sim" e "Não"?
This comment was minimized by the moderator on the site
Hello, Emilly
To solve your problem, please apply the below code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("A1") = "Yes" Then
ActiveSheet.Shapes("Oval 1").Fill.ForeColor.RGB = vbRed
Else
If Range("A1") = "No" Then
ActiveSheet.Shapes("Oval 1").Fill.ForeColor.RGB = vbGreen
End If
End If
End Sub


Please have a try, hope it can help you!
This comment was minimized by the moderator on the site
Hi Skyyang,

I tried the original VBA code and got it to work, although it would not activate actively when the cell changed. Today the code is not working and I also tried your more simplistic code and still did not work. The only thing that changed is that I copied the worksheet which contained the code that worked. Would this then result in it not working?
This comment was minimized by the moderator on the site
Hola, excelente ejemplo.
Pero como seria si tengo una forma y quiero ir coloreado poco a poco dependiendo del valor ejemplo:
Si el valor es 50%
Seia mitad roja y mitad verde
Pero que se vaya llenando según el porcentaje vaya aumentando
Rated 4 out of 5
This comment was minimized by the moderator on the site
I am new to VBAs and am struggling with something. I need to have 9 different cells A1-A9 change the colour of 9 different objects. Objects are cubes 1-9. Just to clarify, each cell is to change just one object A1-Cube 1, etc. Red if it fails to meet the value and green if it exceeds the value. The pass/fail value can change so instead of having the value in the VBA I need it to reference cell A10 which has the pass/fail value. Any chance someone could through out a sample code for me to work with.

Thanks
This comment was minimized by the moderator on the site
Great solution! How can I do if I have more than 1 oval in the worksheet which the colors change according to the value input say in A1, B1,C1? Thanks in advance for your reply! 
This comment was minimized by the moderator on the site
Hello mnsosa,Glad to help. Please copy and paste the below VBA code into the blank Module window.
Sub TestMacro2()
Dim dblHt As Double
Dim rngC As Range
Dim lngr As Long
Dim dblMargin As Double
Dim lngSR As Long

lngSR = 2 'Row where the data starts

dblMargin = 6 ' Distance between shapes

'On Error Resume Next
ActiveSheet.Shapes.SelectAll
Selection.Delete
On Error GoTo 0


dblHt = Rows(lngSR).Height * 4

For lngr = lngSR To Cells(lngSR, "A").End(xlDown).Row
ActiveSheet.Shapes.AddShape(msoShapeOval, _
Cells(lngSR, "D").Left + ((lngr - lngSR) Mod 4) * dblHt + dblMargin, _
Cells(lngSR, "D").Top + Int((lngr - lngSR) / 4) * dblHt + dblMargin, _
dblHt - 2 * dblMargin, _
dblHt - 2 * dblMargin).Select
Selection.Name = "Round" & Cells(lngr, "A").Address
Selection.ShapeRange.TextFrame2.VerticalAnchor = msoAnchorMiddle
Selection.ShapeRange(1).TextFrame2.TextRange.Characters.Text = Cells(lngr, "A").Value
With Selection.ShapeRange(1).TextFrame2.TextRange.Characters(1, 2).ParagraphFormat
.FirstLineIndent = 0
.Alignment = msoAlignCenter
End With
With Selection.ShapeRange(1).TextFrame2.TextRange.Characters(1, 2).Font
.Bold = msoTrue
.Fill.Visible = msoTrue
.Fill.ForeColor.ObjectThemeColor = msoThemeColorText1
.Fill.ForeColor.TintAndShade = 0
.Fill.ForeColor.Brightness = 0
.Fill.Transparency = 0
.Fill.Solid
.Size = 12
End With
With Selection.ShapeRange.Fill
.Visible = msoTrue
If Cells(lngr, "A").Value > 70 Then
.ForeColor.RGB = RGB(0, 176, 80)
ElseIf Cells(lngr, "A").Value >= 40 Then
.ForeColor.RGB = RGB(255, 255, 70)
Else
.ForeColor.RGB = RGB(255, 0, 0)
End If
.Transparency = 0
.Solid
End With
Next lngr
Range("A1").Select
End Sub

After you run the VBA code above, you will see multiple shapes are generated, and the colors of these shapes are changed according to the VBA.Please see my screenshot. Hope it can help. Have a nice day.Sincerely,Mandy
This comment was minimized by the moderator on the site
¿Cómo hacemos si tenemos más de 1 Oval en la hoja de trabajo cuyos colores cambian de acuerdo con el valor ingresado, por ejemplo, en A1, B1, C1...? Mil gracias por su ayuda!

This comment was minimized by the moderator on the site
Hello María Noel,
Glad to help. Please copy and paste the below VBA code into the blank Module window.

Sub TestMacro2()
Dim dblHt As Double
Dim rngC As Range
Dim lngr As Long
Dim dblMargin As Double
Dim lngSR As Long

lngSR = 2 'Row where the data starts

dblMargin = 6 ' Distance between shapes

'On Error Resume Next
ActiveSheet.Shapes.SelectAll
Selection.Delete
On Error GoTo 0


dblHt = Rows(lngSR).Height * 4

For lngr = lngSR To Cells(lngSR, "A").End(xlDown).Row
ActiveSheet.Shapes.AddShape(msoShapeOval, _
Cells(lngSR, "D").Left + ((lngr - lngSR) Mod 4) * dblHt + dblMargin, _
Cells(lngSR, "D").Top + Int((lngr - lngSR) / 4) * dblHt + dblMargin, _
dblHt - 2 * dblMargin, _
dblHt - 2 * dblMargin).Select
Selection.Name = "Round" & Cells(lngr, "A").Address
Selection.ShapeRange.TextFrame2.VerticalAnchor = msoAnchorMiddle
Selection.ShapeRange(1).TextFrame2.TextRange.Characters.Text = Cells(lngr, "A").Value
With Selection.ShapeRange(1).TextFrame2.TextRange.Characters(1, 2).ParagraphFormat
.FirstLineIndent = 0
.Alignment = msoAlignCenter
End With
With Selection.ShapeRange(1).TextFrame2.TextRange.Characters(1, 2).Font
.Bold = msoTrue
.Fill.Visible = msoTrue
.Fill.ForeColor.ObjectThemeColor = msoThemeColorText1
.Fill.ForeColor.TintAndShade = 0
.Fill.ForeColor.Brightness = 0
.Fill.Transparency = 0
.Fill.Solid
.Size = 12
End With
With Selection.ShapeRange.Fill
.Visible = msoTrue
If Cells(lngr, "A").Value > 70 Then
.ForeColor.RGB = RGB(0, 176, 80)
ElseIf Cells(lngr, "A").Value >= 40 Then
.ForeColor.RGB = RGB(255, 255, 70)
Else
.ForeColor.RGB = RGB(255, 0, 0)
End If
.Transparency = 0
.Solid
End With
Next lngr
Range("A1").Select
End Sub

After you run the VBA code above, you will see multiple shapes are generated, and the colors of these shapes are changed according to the VBA.
Please see my screenshot. Hope it can help. Have a nice day.
Sincerely,
Mandy
This comment was minimized by the moderator on the site
Hi... excellent solution... but how do I apply it to multiple shapes based on the corresponding values of a range of cells. Many thanks in advance for your help.
This comment was minimized by the moderator on the site
Hello Ryan,
Glad to help. Please copy and paste the below VBA code into the blank Module window.

Sub TestMacro2()
Dim dblHt As Double
Dim rngC As Range
Dim lngr As Long
Dim dblMargin As Double
Dim lngSR As Long

lngSR = 2 'Row where the data starts

dblMargin = 6 ' Distance between shapes

'On Error Resume Next
ActiveSheet.Shapes.SelectAll
Selection.Delete
On Error GoTo 0


dblHt = Rows(lngSR).Height * 4

For lngr = lngSR To Cells(lngSR, "A").End(xlDown).Row
ActiveSheet.Shapes.AddShape(msoShapeOval, _
Cells(lngSR, "D").Left + ((lngr - lngSR) Mod 4) * dblHt + dblMargin, _
Cells(lngSR, "D").Top + Int((lngr - lngSR) / 4) * dblHt + dblMargin, _
dblHt - 2 * dblMargin, _
dblHt - 2 * dblMargin).Select
Selection.Name = "Round" & Cells(lngr, "A").Address
Selection.ShapeRange.TextFrame2.VerticalAnchor = msoAnchorMiddle
Selection.ShapeRange(1).TextFrame2.TextRange.Characters.Text = Cells(lngr, "A").Value
With Selection.ShapeRange(1).TextFrame2.TextRange.Characters(1, 2).ParagraphFormat
.FirstLineIndent = 0
.Alignment = msoAlignCenter
End With
With Selection.ShapeRange(1).TextFrame2.TextRange.Characters(1, 2).Font
.Bold = msoTrue
.Fill.Visible = msoTrue
.Fill.ForeColor.ObjectThemeColor = msoThemeColorText1
.Fill.ForeColor.TintAndShade = 0
.Fill.ForeColor.Brightness = 0
.Fill.Transparency = 0
.Fill.Solid
.Size = 12
End With
With Selection.ShapeRange.Fill
.Visible = msoTrue
If Cells(lngr, "A").Value > 70 Then
.ForeColor.RGB = RGB(0, 176, 80)
ElseIf Cells(lngr, "A").Value >= 40 Then
.ForeColor.RGB = RGB(255, 255, 70)
Else
.ForeColor.RGB = RGB(255, 0, 0)
End If
.Transparency = 0
.Solid
End With
Next lngr
Range("A1").Select
End Sub

After you run the VBA code above, you will see multiple shapes are generated, and the colors of these shapes are changed according to the VBA.
Please see my screenshot. Hope it can help. Have a nice day.
Sincerely,
Mandy
This comment was minimized by the moderator on the site
How do I make the private sub to read the result from the AVERAGE(C1,C5,C9) calculation?

Sub only works with numeric values; any thoughts and suggestions are greatly appreciated.
This comment was minimized by the moderator on the site
Hello Cesare,How are you? I notice that the VBA code can work with the AVERAGE(number, number...) calculation. But the trick is that every time you change the values in the calculation, you need to double-click the formula in the cell to make the VBA work again. 
For example, In cell A1, after we input the formula is =AVERAGE(C2:D3), the VBA works and changes the color of the shape accordingly. Please see screenshot 1. <span style="letter-spacing: 0.2px; color: inherit; font-family: inherit; font-style: inherit; font-variant-ligatures: inherit; font-variant-caps: inherit; font-weight: inherit;">C2:D3, the returned result in cell A1 changes, but the shape color hasn't been changed yet. In this case, we need to double click the formula in cell A1 to make the VBA work. Then the shape color will be changed accordingly. Please see screenshots 2 and 3.</span>
This comment was minimized by the moderator on the site
Thanks for this which is really useful.

I now want to use it with a pivot table on another worksheet which controls the data on the sheet with the shapes that I want to change colour. However, when I change the selection on the pivot table the data on the worksheet with the shapes is updated but the code does not run so the shapes do not change colour

If I manually change the values the code runs and the colour of the shapes is updated.

Question: what do i need to add to the code above to allow it to run automatically?
This comment was minimized by the moderator on the site
How can this be applied if you have multiple shape in the same worksheet?
This comment was minimized by the moderator on the site
Hello Yasir,
Glad to help. Please copy and paste the below VBA code into the blank Module window.

Sub TestMacro2()
Dim dblHt As Double
Dim rngC As Range
Dim lngr As Long
Dim dblMargin As Double
Dim lngSR As Long

lngSR = 2 'Row where the data starts

dblMargin = 6 ' Distance between shapes

'On Error Resume Next
ActiveSheet.Shapes.SelectAll
Selection.Delete
On Error GoTo 0


dblHt = Rows(lngSR).Height * 4

For lngr = lngSR To Cells(lngSR, "A").End(xlDown).Row
ActiveSheet.Shapes.AddShape(msoShapeOval, _
Cells(lngSR, "D").Left + ((lngr - lngSR) Mod 4) * dblHt + dblMargin, _
Cells(lngSR, "D").Top + Int((lngr - lngSR) / 4) * dblHt + dblMargin, _
dblHt - 2 * dblMargin, _
dblHt - 2 * dblMargin).Select
Selection.Name = "Round" & Cells(lngr, "A").Address
Selection.ShapeRange.TextFrame2.VerticalAnchor = msoAnchorMiddle
Selection.ShapeRange(1).TextFrame2.TextRange.Characters.Text = Cells(lngr, "A").Value
With Selection.ShapeRange(1).TextFrame2.TextRange.Characters(1, 2).ParagraphFormat
.FirstLineIndent = 0
.Alignment = msoAlignCenter
End With
With Selection.ShapeRange(1).TextFrame2.TextRange.Characters(1, 2).Font
.Bold = msoTrue
.Fill.Visible = msoTrue
.Fill.ForeColor.ObjectThemeColor = msoThemeColorText1
.Fill.ForeColor.TintAndShade = 0
.Fill.ForeColor.Brightness = 0
.Fill.Transparency = 0
.Fill.Solid
.Size = 12
End With
With Selection.ShapeRange.Fill
.Visible = msoTrue
If Cells(lngr, "A").Value > 70 Then
.ForeColor.RGB = RGB(0, 176, 80)
ElseIf Cells(lngr, "A").Value >= 40 Then
.ForeColor.RGB = RGB(255, 255, 70)
Else
.ForeColor.RGB = RGB(255, 0, 0)
End If
.Transparency = 0
.Solid
End With
Next lngr
Range("A1").Select
End Sub

After you run the VBA code above, you will see multiple shapes are generated, and the colors of these shapes are changed according to the VBA.
Please see my screenshot. Hope it can help. Have a nice day.
Sincerely,
Mandy
This comment was minimized by the moderator on the site
Great vba solution.

It is possible to also use conditional formatting to colour the shapes.

Set the name of each shape as the cell value. Using a With Each Shape then set the shape colour as the cell colour for all named shapes.

The cell colour may be changed using conditional formatting based on numerical values.

For example the colour of a semi transparent overlap on a city map can be used to graphically indicate population density per block with a graduated colour scheme.
This comment was minimized by the moderator on the site
Can you share an example of the code?
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations