2

我从相同的工作簿中复制了一些图表,但每个图表的源数据(42 个图表,每个有 6 个系列)仍然包含完整的文件名路径。源表和单元格是相同的,所以我只想找到路径字符串并将其替换为“”。但是,我找不到获取源数据名称的方法(因为它出现在 refedit 框中)。从那里,我可以更换我需要的东西。

我们拥有的是这样的:

ActiveChart.SeriesCollection(1).Values = "='C:\[oldfile.xls]Charts.Data'!R1C17:R1C28"

而且我只想将“”中的部分作为字符串,并执行我的功能以删除文件路径。如果我尝试从中获取字符串,即:

sourcestring = ActiveChart.SeriesCollection(1).Values

我收到一个错误;似乎VBA在读取它时认为它是一个数组,但在分配给它时可以使用一个字符串。有任何想法吗?

4

1 回答 1

1

你是对的,你不能真正得到显示在 refedit 框中的相同公式......你必须操纵你正在使用的系列的 .Formula 或 .FormulaR1C1 属性,并重建公式并设置到 values 和/或 xvalues 属性。

这段代码应该可以工作,有一些函数可以提取公式的不同部分......我认为它应该适合你,或者至少希望能帮助你找出最好的方法......

Sub ChangeActiveChartData()
    ChangeChartData ActiveChart
End Sub

Sub ChangeChartData(TheChart As Chart)
    If TheChart Is Nothing Then Exit Sub

    Dim TheSeries As Series
    Set TheSeries = TheChart.SeriesCollection(1)

    Dim TheForm As String
    TheForm = TheSeries.FormulaR1C1

    Dim XValsForm As String
    XValsForm = GetXValuesFromFormula(TheForm)
    Debug.Print XValsForm
    XValsForm = GetRangeFormulaFromFormula(XValsForm)
    Debug.Print XValsForm

    Dim ValsForm As String
    ValsForm = GetValuesFromFormula(TheForm)
    Debug.Print ValsForm
    ValsForm = GetRangeFormulaFromFormula(ValsForm)
    Debug.Print ValsForm

    XValsForm = "=" & TheChart.Parent.Parent.Name & "!" & XValsForm ' TheChart's parents parent is the worksheet; we're assuming the chart is embedded in a worksheet
    ValsForm = "=" & TheChart.Parent.Parent.Name & "!" & ValsForm

    TheSeries.XValues = XValsForm
    TheSeries.Values = ValsForm

End Sub

Function GetXValuesFromFormula(SeriesFormula As String) As String
    ' Find string between first and second commas
    Dim FormulaParts() As String
    FormulaParts = Split(SeriesFormula, ",")
    GetXValuesFromFormula = FormulaParts(1)

End Function

Function GetValuesFromFormula(SeriesFormula As String) As String
    ' Find string between second and third commas
    Dim FormulaParts() As String
    FormulaParts = Split(SeriesFormula, ",")
    GetValuesFromFormula = FormulaParts(2)

End Function

Function GetRangeFormulaFromFormula(TheFormula As String) As String
    ' return to the right of the ! character in theformula
    Dim ExclamPos As Integer
    ExclamPos = InStrRev(TheFormula, "!")
    If ExclamPos > 0 Then
        GetRangeFormulaFromFormula = Right(TheFormula, Len(TheFormula) - ExclamPos)
    Else
        GetRangeFormulaFromFormula = TheFormula
    End If
End Function
于 2009-03-03T14:37:49.277 回答