선택한 차트에서 매크로 실행

선택한 차트에서 매크로 실행

스프레드시트의 차트에 몇 가지 빠른 옵션을 추가하고, 차트를 선택하고 체크박스를 선택/선택 취소하면 코드가 실행됩니다.

체크박스 코드는 다음과 같습니다.

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

관련 정보