为每个图表去除 VBA 中的特定单词

Strip Specific Word in VBA for each chart

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

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: abc 图例中删除 "Test: 一词,然后得到结果图例为 abc。我想我可以修改下面的代码,但我不知道该怎么做。 :

For i = ActiveChart.SeriesCollection.Count To 1 Step -1
If ActiveChart.Legend(i)= "Test: *" Then
ActiveChart.Legend(i) **what I think needs to be modified**
End If
Next i

要删除特定单词,您可以

  • 使用函数替换前缀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