【发布时间】:2017-08-04 09:23:18
【问题描述】:
我有一个包含两个图表的电子表格,我想根据表格中的值在其中一个系列点旁边添加一些文本框。
我为此创建了两个程序,每个程序都有自己的优点和缺点:
Sub add_comments(apply_to As Series, source_range As Range)
Dim i As Long
Dim c As Range
If source_range.Count > apply_to.Points.Count Then
Set source_range = source_range.Resize(apply_to.Points.Count, 1)
End If
i = 1
For Each c In source_range
If Not IsError(c) And i <= apply_to.Points.Count Then
If Len(c.Text) <> 0 Then
apply_to.Points(i).HasDataLabel = True
apply_to.Points(i).DataLabel.Text = c.Value2
apply_to.Points(i).DataLabel.Format.AutoShapeType = msoShapeRectangularCallout
With apply_to.Points(i).DataLabel.Format.Line
.Visible = msoTrue
.ForeColor.RGB = RGB(0, 0, 0)
End With
apply_to.Points(i).DataLabel.Position = xlLabelPositionAbove
Else
If apply_to.Points(i).HasDataLabel Then
apply_to.Points(i).DataLabel.Delete
End If
End If
End If
i = i + 1
Next c
End Sub
上面的代码使用了标签,这是非常理想的,除了我不能重新定位标签,当它们重叠时它会变得有点难看。
Sub alternative_comments(apply_to As Series, source_range As Range)
Dim c As Range
Dim i As Long
If source_range.Count > apply_to.Points.Count Then
Set source_range = source_range.Resize(apply_to.Points.Count, 1)
End If
i = 1
For Each c In source_range
If Not IsError(c) And i <= apply_to.Points.Count Then
If Len(c.Text) <> 0 Then
With SPC_01.Shapes.AddLabel(msoTextOrientationHorizontal, 100, 100, 10, 10)
.TextFrame2.TextRange.Characters.Text = c.Text
With .Line
.Visible = msoTrue
.ForeColor.RGB = RGB(0, 0, 0)
End With
.Top = apply_to.Points(i).Top - .Height
.Left = apply_to.Points(i).Left - .Width
Debug.Print apply_to.Points(i).Top & " - " & .Top
Debug.Print apply_to.Points(i).Left & " - " & .Left
End With
End If
End If
i = i + 1
Next c
End Sub
另一种解决方案使用文本框,非常适合移动和调整大小,但不会自动缩放以适应文本,我也找不到任何明智的方法。
正如您所见,我对这两种方法都感到困惑,尽管我觉得使用标签的缺点比使用文本框要轻一些。但是,我想知道你们中是否有人能告诉我自动将 cmets 添加到系列中的数据点的最佳方法是什么?我在正确的轨道上吗?
我也有posted this question to the VBAExpress forums,如果你们有谁想看看整个工作簿。
【问题讨论】:
-
我认为您最好的选择是首先计算哪些点将获得数据标签,然后计算出数据标签可以具有的最大宽度。这个宽度可能太小了,你可以使用 datalabel.top 属性来改变数据标签相对于图表顶部的位置,并将标签放在一个上面。
-
@Luuklag 是的,这似乎是我最好的选择。想办法防止它们重叠将是一个绝对的痛苦:-|非常感谢您的建议,我已经在使用它方面取得了一些进展。
标签: vba excel excel-2016