使用VBA更改excel中的图表标题

时间:2018-01-08 15:14:06

标签: excel vba

我需要选择一些图表并替换其标题中的公共部分

我尝试编写此代码但不起作用!

Sub ChangeTitelFormula()
''' Just do active chart
If ActiveChart Is Nothing Then
    '' There is no active chart
    MsgBox "Please select a chart and try again.", vbExclamation, _
        "No Chart Selected"
    Exit Sub
End If

Dim OldString As String, NewString As String, strTemp As String
Dim mySrs As ChartObject

OldString = InputBox("Enter the string to be replaced:", "Enter old string")

If Len(OldString) > 1 Then
    NewString = InputBox("Enter the string to replace " & """" _
        & OldString & """:", "Enter new string")
    '' Loop through all series
    For Each mySrs In ActiveChart.ChartObjects
        strTemp = WorksheetFunction.Substitute(mySrs.ChartTitle.Text, _
            OldString, NewString)
        mySrs.Chart.ChartTitle.Text = strTemp
    Next
Else
    MsgBox "Nothing to be replaced.", vbInformation, "Nothing Entered"
End If
End Sub

任何帮助? 感谢

2 个答案:

答案 0 :(得分:1)

我对你的代码进行了小手术。此例程仅执行活动图表:

Sub FindReplaceForChartTitle()
  Dim OldString As String, NewString As String, strTemp As String

  '' Just do active chart
  If ActiveChart Is Nothing Then
    MsgBox "Please select a chart and try again.", vbExclamation, _
      "No Chart Selected"
    Exit Sub
  End If

  OldString = InputBox("Enter the string to be replaced:", "Enter old string")

  If Len(OldString) > 1 Then
    NewString = InputBox("Enter the string to replace " & """" _
      & OldString & """:", "Enter new string")

    strTemp = WorksheetFunction.Substitute(ActiveChart.ChartTitle.Text, _
      OldString, NewString)
    ActiveChart.ChartTitle.Text = strTemp
  Else
    MsgBox "Nothing to be replaced.", vbInformation, "Nothing Entered"
  End If
End Sub

此例程执行活动工作表中的所有图表:

Sub FindReplaceForChartTitles()
  Dim OldString As String, NewString As String, strTemp As String
  Dim chob As ChartObject

  OldString = InputBox("Enter the string to be replaced:", "Enter old string")

  If Len(OldString) > 1 Then
    NewString = InputBox("Enter the string to replace " & """" _
      & OldString & """:", "Enter new string")

    For Each chob In ActiveSheet.ChartObjects
      If chob.Chart.HasTitle Then
        strTemp = WorksheetFunction.Substitute(chob.Chart.ChartTitle.Text, _
          OldString, NewString)
        chob.Chart.ChartTitle.Text = strTemp
      End If
    Next
  Else
    MsgBox "Nothing to be replaced.", vbInformation, "Nothing Entered"
  End If
End Sub

答案 1 :(得分:0)

可能您的ActiveChart没有ChartObjects。 试试ActiveChart.ChartTitle.Text