我有一些我从同一个工作簿中复制过的图表,但每个图表的源数据(42个图表,每个图表中有6个系列)仍包含完整的文件名路径。源表和单元格是相同的,所以我只想找到路径字符串并将其替换为“”。但是,我找不到获取sourcedata名称的方法(因为它出现在refedit框中)。从那里,我可以取代我需要的东西。
我们拥有的是:
ActiveChart.SeriesCollection(1).Values = "='C:\[oldfile.xls]Charts.Data'!R1C17:R1C28"
我只想将“”中的部分作为字符串,并执行我的函数来删除文件路径。如果我尝试从中获取一个字符串,即:
sourcestring = ActiveChart.SeriesCollection(1).Values
我收到错误;看起来VBA在从它读取时认为它是一个数组,但在分配它时可以使用一个字符串。有什么想法吗?
答案 0 :(得分:1)
你是对的,你不能真正得到在refedit框中显示的相同公式...你必须操纵你正在使用的系列上的.Formula或.FormulaR1C1属性,并重建公式并将其设置为值和/或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