在VBA中为每个图表剥离特定字

时间:2016-06-20 16:44:58

标签: vba excel-vba legend excel

所以我使用以下代码遍历每个图表:

Sub LoopThroughCharts()

Dim sht As Worksheet
Dim CurrentSheet As Worksheet
Dim cht As ChartObject

Application.ScreenUpdating = False
Application.EnableEvents = False

Set CurrentSheet = ActiveSheet

For Each sht In ActiveWorkbook.Worksheets
  For Each cht In sht.ChartObjects
    cht.Activate

    'Do something with the chart...
    ActiveChart.Legend.Select
    Selection.Left = 108.499
    Selection.Width = 405.5
    Selection.Height = 36.248
    Selection.Top = 201.85
    Selection.Left = 63.499
    Selection.Top = 330.85
    ActiveChart.PlotArea.Select
    Selection.Height = 246.69
    Selection.Width = 445.028

  Next cht
Next sht

CurrentSheet.Activate
Application.EnableEvents = True

这使得每个图表都具有特定的大小,我认为我可以修改以下vba代码,从"Test:图例中删除单词Test: abc,然后生成的图例将是{{1 }}。我认为我可以修改以下代码,但我不知道该怎么做。 :

abc

1 个答案:

答案 0 :(得分:1)

为了删除特定单词,您可以

  • 使用函数Replace()
  • 替换前缀
  • 使用函数Mid()
  • 获取子字符串

这是演示代码

Sub stripDemo()
    Dim str As String
    str = "Test: my legend"
    Debug.Print Replace(str, "Test: ", "")
    Debug.Print Mid(str, 7, Len(str) - 6)
End Sub

修改

因此,当代码应用于图表时,它变为:

For Each sht In ActiveWorkbook.Worksheets
  For Each cht In sht.ChartObjects
    cht.Activate
    ' iterate the series collection
    ' replace the prefixe "Tests: " with ""
    For Each sr In ActiveChart.SeriesCollection
      If Len(sr.Name) > 6 And Left(sr.Name, 6) = "Test: " Then
        sr.Name = Replace(sr.Name, "Test: ", "")
      End If
    Next sr
  Next cht
Next sht