问题
I am writing some code to loop through each data point in a chart and change the color (fill/border) of the point marker if it is the wrong color. I don't want it to change if it is a compliant color (using a select case).
Problem: Checking markerbackgroundcolor and markerforegroundcolor returns "-1" no matter what the color is until i manually change the color (right click marker and change fill from automatic to solid).Something to do with Automatic colors.
Basic example in immediate window (after inserted scatter chart without changing formatting):
?Activechart.SeriesCollection(1).points(1).markerbackgroundcolor
returns
-1
Then without doing anything else:
Activechart.SeriesCollection(2).points(1).markerbackgroundcolor=255
?Activechart.SeriesCollection(2).points(1).markerbackgroundcolor
255
Is there another property of the marker I can test instead? Or another approach entirely? The checking of the color itself is critical to other parts of the code so all the work arounds I've tried so far are not cutting it : (
PS new user, apologies if haven't formulated question too well.
回答1:
I don't think that you can change individual data points (or, at least I don't know how). I think that the problem lies in checking for "compliant colors." This type of color property seems to require a Long value which corresponds to a color.
This code worked for me (Excel 2007) on a line-chart in chart I created for a project (I added the Debug.Print
lines to show the numbers returned for Series in my chart)...
Sub formatTable()
Dim wb As Workbook
Dim ws As Worksheet
Dim co As ChartObject
Dim c As Integer
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Sheet1")
Set co = ws.ChartObjects("Chart1")
With co.Chart
Debug.Print .Name
For c = 1 To .SeriesCollection.Count
Debug.Print .SeriesCollection(c).Name
Debug.Print "Foreground Color: " & .SeriesCollection(c).MarkerForegroundColorIndex 'Get Forground Color
Debug.Print "Background Color: " & .SeriesCollection(c).MarkerBackgroundColorIndex ' Get Background color
.SeriesCollection(c).MarkerForegroundColorIndex = 5 'Set foreground to Blue
.SeriesCollection(c).MarkerBackgroundColorIndex = 42 ' Set background to Lt Blue
Next c
End With
End Sub
After re-reading your question, I dug a little deeper to see how to check or set the color for a Point
. All you should need to do is embed another FOR
loop inside of the above code. The important thing in this line is to use: .SeriesCollection(c).Points.Item(i).Marker... = Value
来源:https://stackoverflow.com/questions/22139904/fill-and-border-color-property-of-data-point-marker-scatter-or-line-excel-vba