我正在尝试使用VBA来更改几个图表的系列以使用动态范围而不是静态单元格范围。每次得到一个模糊的1004应用程序错误。
这是我的代码:
Sub test20()
Dim wks As Worksheet, tbl As ListObject
Dim arr()
arr = [{"Date","1/1/2016","2/1/2016","3/1/2016","4/1/2016","5/1/2016","6/1/2016";"Green",100,200,300,400,350,425;"Yellow",350,250,150,50,75,125;"Red",10,7,5,3,25,45}]
Set wks = ActiveSheet
wks.Range("a1:D7") = WorksheetFunction.Transpose(arr)
Set tbl = wks.ListObjects.Add(xlSrcRange, wks.Range("a1").CurrentRegion, , xlYes)
tbl.Name = "tblTix"
'Dynamic ranges
ActiveWorkbook.Names.Add Name:="rngLbl_1", RefersToR1C1:="=OFFSET(tblTix,MATCH(MAX(tblTix[Date]),tblTix[Date],1)-3,MATCH(""Date"",tblTix[#Headers],0)-1,1,1)"
ActiveWorkbook.Names.Add Name:="rngLbl_2", RefersToR1C1:="=OFFSET(tblTix,MATCH(MAX(tblTix[Date]),tblTix[Date],1)-2,MATCH(""Date"",tblTix[#Headers],0)-1,1,1)"
ActiveWorkbook.Names.Add Name:="rngLbl_3", RefersToR1C1:="=OFFSET(tblTix,MATCH(MAX(tblTix[Date]),tblTix[Date],1)-1,MATCH(""Date"",tblTix[#Headers],0)-1,1,1)"
ActiveWorkbook.Names.Add Name:="rngDat_1", RefersToR1C1:="=OFFSET(tblTix,MATCH(MAX(tblTix[Date]),tblTix[Date],0)-3,1,1,3)"
ActiveWorkbook.Names.Add Name:="rngDat_2", RefersToR1C1:="=OFFSET(tblTix,MATCH(MAX(tblTix[Date]),tblTix[Date],0)-2,1,1,3)"
ActiveWorkbook.Names.Add Name:="rngDat_3", RefersToR1C1:="=OFFSET(tblTix,MATCH(MAX(tblTix[Date]),tblTix[Date],0)-1,1,1,3)"
'Static ranges to test, just in case
ActiveWorkbook.Names.Add Name:="rngStatLbl", RefersTo:="=Sheet1!$B$1:$D$1"
ActiveWorkbook.Names.Add Name:="rngStatData", RefersTo:="=Sheet1!$B$3:$D$3"
Range("A1").Select
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$D$1,Sheet1!$A$3:$D$5")
MsgBox "Modify the chart > Select Data > Switch Row Column", vbOKOnly
Stop
ActiveChart.SeriesCollection(1).Formula = "=SERIES(Sheet1!$B$1,Book1.xlsx!rngLbl_1,Book1.xlsx!rngDat_1,1)"
'This value was pulled using VBA after the change was made in the GUI
ActiveChart.SeriesCollection(1).Formula = "=SERIES(Book1.xlsx!rngLbl_1,Sheet1!$B$1:$D$1,Book1.xlsx!rngDat_1,1)"
End Sub
任何想法如何解决这个问题?在得到this question的答案后,我尝试了
...SeriesCollection(1).Formula = ....
...SeriesCollection(1).FormulaR1C1 = ....
但仍然没有运气。