我在超级用户上找到了Hide data label containing series name if value is zero,但它删除了所有图表值0
的数据标签:
Sub RemoveZeroValueDataLabel()
'runs through every chart on the ActiveSheet
Dim cht As Chart
Dim chtObj As ChartObject
For Each chtObj In ActiveSheet.ChartObjects
Set cht = chtObj.Chart
Dim ser As Series
For Each ser In cht.SeriesCollection
Dim vals As Variant
vals = ser.Values
'include this line if you want to reestablish labels before deleting
ser.ApplyDataLabels xlDataLabelsShowLabel, , , , True, False, False, False, False
'loop through values and delete 0-value labels
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
Next chtObj
End Sub
我自己尝试编辑:
Sub RemoveZeroValueDataLabelonlyonechart()
Dim cht As Chart
Dim chtObj As ChartObject
Set cht = chtObj.Chart
Dim ser As Series
For Each ser In cht.SeriesCollection
Dim vals As Variant
vals = ser.Values
'include this line if you want to reestablish labels before deleting
ser.ApplyDataLabels xlDataLabelsShowLabel, , , , True, False, False, False, False
'loop through values and delete 0-value labels
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
但是这会回来:
Microsoft visual basic |运行时错误'91'|对象变量或未设置块变量
如何编辑代码以便它只从我选择的图表中删除数据标签,而不是表格中的所有图表?
答案 0 :(得分:0)
x
在原始循环中,chtObj循环ActiveSheet中的所有图表对象。在这里,您只想在特定的Chart对象上进行设置,因此您删除了Dim chtObj As ChartObject
循环,很好。但是你定义为ChartObject的引用的chtObj到目前为止没有引用任何内容。您需要将其分配给某个Chart对象。您需要知道要修改的Chart对象的名称或索引。然后你将在上面的一行之后添加一个简单的行:
For
或者,如果图表是在该工作表中创建的第一个图表:
Set chtObj = ActiveSheet.ChartObjects("someName")
添加这两行中的一行后,使用与目标Chart对应的相应名称或编号,其余代码应该可以正常工作。