我正在使用聚集柱形圖,我正在嘗試找到一種方法來更改每種顏色的顏色圖表。有人可以解決我的問題嗎?謝謝
編輯:我正在嘗試通過 vba 代碼來實作這一點
uj5u.com熱心網友回復:
假設您知道如何手動更改系列的顏色,這是使用宏記錄器的好地方。錄制時,宏錄制器會將您在 Excel 中所做的所有操作“翻譯”為 VBA 代碼。 https://support.microsoft.com/en-us/office/automate-tasks-with-the-macro-recorder-974ef220-f716-4e01-b015-3ea70e64937b
我制作了一個示例聚類柱形圖來演示這一點。它位于 Sheet1 上。首先,我轉到 Excel 中的“開發人員”選項卡,然后在“代碼”面板下,單擊“記錄宏”按鈕。然后,我手動將系列顏色更改為其他顏色,然后單擊停止錄制。以下是宏記錄器記錄的內容:
Option Explicit
Sub ChangeCol()
'
' ChangeCol Macro
'
'
ActiveSheet.ChartObjects("Chart 1").Activate
ActiveChart.FullSeriesCollection(2).Select
With Selection.Format.Fill
.Visible = msoTrue
.ForeColor.ObjectThemeColor = msoThemeColorAccent4
.ForeColor.TintAndShade = 0
.ForeColor.Brightness = -0.25
.Transparency = 0
.Solid
End With
End Sub
這里有很多我們不關心的額外代碼,但這就是宏記錄器的本質。它是一個很好的工具,可以為您指明正確的方向,但它很少能準確地為您提供所需的東西。
所以這里是來自宏記錄器的相同代碼,但沒有所有額外的代碼:
Option Explicit
Sub ChangeCol()
'
' ChangeCol Macro
'
'
ActiveSheet.ChartObjects("Chart 1").Activate
ActiveChart.FullSeriesCollection(2).Select
With Selection.Format.Fill
.ForeColor.ObjectThemeColor = msoThemeColorAccent4 ' This changes the color
End With
End Sub
這段代碼更簡潔,但我們可以做得更好。.Activate和.Select方法通常是我們可以像這樣擺脫的東西:
Option Explicit
Sub ChangeCol()
'
' ChangeCol Macro
'
'
' Reference the chart
Dim MyChart As ChartObject
Set MyChart = ThisWorkbook.Sheets("Sheet1").ChartObjects("Chart 1")
' Change the chart's series 2 color
With MyChart.Chart.FullSeriesCollection(2).Format.Fill
.ForeColor.ObjectThemeColor = msoThemeColorAccent4
End With
End Sub
但是,如果您想使用自己的顏色而不是其中一種主題顏色怎么辦?您可以使用.RGB方法而不是.ObjectThemeColor方法。當我們這樣做的時候,讓我們讓整個子更通用,以便我們可以將它用于集群圖表中的任何系列:
Option Explicit
Sub ChangeCol(ClusteredChart As Chart, SeriesNumber As Long, Red As Byte, Green As Byte, Blue As Byte)
Clustered.Chart.FullSeriesCollection(SeriesNumber).Format.Fill.ForeColor.RGB = RGB(Red, Blue, Green)
End Sub
就這樣,一個用于更改群集圖表中系列顏色的子程式。這就是那個 sub 的呼叫方式:
Private Sub Test()
Dim MyChart As Chart
Set MyChart = ThisWorkbook.Sheets("Sheet1").ChartObjects("Chart 1").Chart
ChangeCol ClusteredChart:=MyChart, SeriesNumber:=2, Red:=0, Blue:=55, Green:=55
End Sub
More importantly than the result of this process, I hope you understand the process itself. Excel's Macro Recorder is a powerful tool for all levels of VBA programmer, and it's a god-send especially when you know how to manually do something, and want to automate it.
Finally, this sub that I've presented is not complete, and that's where you can fix it. For example, there is no check to see if the passed SeriesNumber even exists. And you'll notice that this sub only changes one series' color. If you want to iterate through all series, you'll either have to modify this sub, or do the iteration outside of it and call the sub multiple times.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/437788.html
下一篇:框和文本問題
