以下代码允许用户从命名图表中删除值为零的图表数据标签。
要选择图表,用户必须在宏中输入图表名称。
在此示例中,名称为“Chart abc”。
如何构建代码,以便用户只需单击图表即可选择图表?
Sub DeleteZeroValueLabelsfromSelectedChart()
' If ActiveChart Is Nothing Then
' MsgBox "No chart selected. Please select a chart."
' Else
Dim cht As Chart
Dim chtObj As ChartObject
Set chtObj = ActiveSheet.ChartObjects("Chart abc") 'SET
Set cht = chtObj.Chart
Dim ser As Series
For Each ser In cht.SeriesCollection
Dim vals As Variant
vals = ser.Values
Dim i As Integer
For i = LBound(vals) To UBound(vals)
If vals(i) = 0 Then
With ser.Points(i)
If .HasDataLabel Then
.DataLabel.Delete
End If
End With
End If
Next i
Next ser
End Sub
怎么说:
Set chtObj = ActiveChart
一种可能性:
Sub DeleteZeroValueLabelsfromSelectedChart_v1()
If ActiveChart Is Nothing Then
MsgBox "No chart selected. Please select a chart."
Else
Dim cht As Chart
' Dim chtObj As ChartObject
' Set chtObj = ActiveSheet.ChartObjects("Chart abc")
' Set cht = chtObj.Chart
Set cht = ActiveChart
Dim ser As Series
For Each ser In cht.SeriesCollection
Dim vals As Variant
vals = ser.Values
Dim i As Integer
For i = LBound(vals) To UBound(vals)
If vals(i) = 0 Then
With ser.Points(i)
If .HasDataLabel Then
.DataLabel.Delete
End If
End With
End If
Next i
Next ser
End If
End Sub