你是对的,你不能真正得到显示在 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