我想在電子表格中的圖表中添加一些快速選項,我想選擇一個圖表,選擇/取消選擇複選框,然後運行程式碼。
複選框代碼是;
Private Sub CheckBox1_Click()
If CheckBox1.Value = True Then
DisplayLabels
Else
HideLabels
End If
End Sub
DisplayLabels 和 HideLabels 程式碼是
Sub DisplayLabels()
With ActiveChart
ActiveChart.FullSeriesCollection(1).Select
ActiveChart.FullSeriesCollection(1).ApplyDataLabels
End With
End Sub
Sub HideLabels()
With ActiveChart
ActiveSheet.ChartObjects("Basic_Chart").Activate
ActiveChart.FullSeriesCollection(1).Select
ActiveChart.FullSeriesCollection(1).DataLabels.Select
Selection.ShowValue = False
End With
End Sub
問題是,一旦我勾選了該框,圖表就不再被選中/活動,因此程式碼無法運作。有沒有解決的辦法。我希望這是多張紙上可重複使用的程式碼,因此不能直接引用圖表。
答案1
忘記複選框,讓巨集確定是否有標籤。下面將檢查是否選擇了圖表,如果是,則切換標籤:
If ActiveChart Is Nothing Then
MsgBox "You must select a chart"
Exit Sub
End If
For Each mySeries In ActiveChart.SeriesCollection
On Error Resume Next
mySeries.DataLabels.Select
If (Err.Number = 0) Then
mySeries.DataLabels.Delete
Else
mySeries.ApplyDataLabels
End If
On Error GoTo 0
Next mySeries