TheTiredEngineer
New Member
- Joined
- Jul 31, 2024
- Messages
- 31
- Office Version
- 365
- Platform
- Windows
Ive got a donut chart in excel with some data. Im trying to adjust the FirstSliceAngle depending on a user input. I keep trying this code and I keep getting an error message at
What am I doing wrong here?
Excel Formula:
pieChart.FirstSliceAngle = angleValue
What am I doing wrong here?
Excel Formula:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim chartObj As ChartObject
Dim pieChart As Chart
Dim ws As Worksheet
Dim angleCell As Range
Dim angleValue As Integer
' Set the worksheet and the cell to monitor for angle changes
Set ws = ThisWorkbook.Sheets("Sheet1") ' Adjust the sheet name
Set angleCell = ws.Range("A1") ' Specify the cell where the angle will be input
' Check if the changed cell is the one we're monitoring
If Not Intersect(Target, angleCell) Is Nothing Then
' Get the new angle value from the cell
angleValue = angleCell.Value
' Ensure the value is between 0 and 360
If angleValue < 0 Or angleValue > 360 Then
MsgBox "Please enter a value between 0 and 360."
Exit Sub
End If
' Set the chart object to "Chart 1"
On Error Resume Next ' Prevent errors if the chart is not found
Set chartObj = ws.ChartObjects("Chart 1")
On Error GoTo 0 ' Resume normal error handling
' Check if the chart exists and is a pie or donut chart
If Not chartObj Is Nothing Then
Set pieChart = chartObj.Chart
If pieChart.ChartType = xlPie Or pieChart.ChartType = xlDoughnut Then
' Set the FirstSliceAngle property to the value from the monitored cell
' Set the FirstSliceAngle property on the chart object, not the PlotArea
On Error GoTo handleError
pieChart.FirstSliceAngle = angleValue
Exit Sub
MsgBox "FirstSliceAngle set to " & angleValue & " for Chart 1"
Else
MsgBox "Chart 1 is not a pie or donut chart."
End If
Else
MsgBox "Chart 1 not found."
End If
End If
End Sub