在图表中定位标签
我有一个包含两个图表的电子表格,其中我想根据表格中的值在一个系列的点之后添加一些文本框。
我为此创build了两个程序,每个程序都有自己的优点和缺点:
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
另一种解决scheme使用文本框,这对移动和resize非常有用,但是不会自动缩放以适应文本,而且我也找不到任何明智的方法来实现这一点。
正如你所看到的,我在这两种方法上都陷入了困境,尽pipe我觉得使用标签的缺点比使用文本框要less一些。 但是,我想知道是否有人可以告诉我什么是一个系列中自动添加评论到数据点的最佳方法? 我在正确的轨道上?
我也发布了这个问题到VBAExpress论坛 ,如果你想看看整个工作簿。
对于文本框的方法,你可以将其设置为autosize使用这个:
.TextFrame2.AutoSize = msoAutoSizeShapeToFitText
然后有两个选项可以改变外观。 你可以设置文字换行:
.TextFrame2.WordWrap = True
这不会改变文本框的宽度,这将会像上面一样垂直地输出文本框。
或者你可以设置它不包装:
.TextFrame2.WordWrap = False
这将水平地串起来,直到遇到换行符。
因此,您可以根据需要设置文本框宽度,然后打开,或者在源文本中添加显式换行符(Alt + Enter),然后closures。