我正在將excel圖表輸出爲powerpoint,我需要向圖表添加新的數據系列,我已經記錄了該宏以查看要做到這一點,它需要一系列的收藏,但沒有運氣。使用vba 2010將新的數據系列添加到現有的excel圖表對象中使用vba 2010 - 類型不匹配
下面是使用Access 2010中的VBA完整工作示例,其中在最後我嘗試添加新的數據系列:
Option Compare Database
Public Sub CreateChart()
Dim myChart As Chart
Dim gChartData As ChartData
Dim gWorkBook As Excel.Workbook
Dim gWorkSheet As Excel.Worksheet
Dim pptApp As Object
Dim pptobj As Object
Set pptApp = CreateObject("Powerpoint.Application")
Set pptobj = pptApp.Presentation.Add
pptobj.Slides.Add 1, ppLayoutBlank
' Create the chart and set a reference to the chart data.
Set myChart = pptobj.Slides(1).Shapes.AddChart.Chart
Set gChartData = myChart.ChartData
' Set the Workbook and Worksheet references.
Set gWorkBook = gChartData.Workbook
Set gWorkSheet = gWorkBook.Worksheets(1)
' Add the data to the workbook.
gWorkSheet.ListObjects("Table1").Resize gWorkSheet.Range("A1:B5")
gWorkSheet.Range("Table1[[#Headers],[Series 1]]").Value = "Items"
gWorkSheet.Range("a2").Value = "Coffee"
gWorkSheet.Range("a3").Value = "Soda"
gWorkSheet.Range("a4").Value = "Tea"
gWorkSheet.Range("a5").Value = "Water"
gWorkSheet.Range("b2").Value = "1000"
gWorkSheet.Range("b3").Value = "2500"
gWorkSheet.Range("b4").Value = "4000"
gWorkSheet.Range("b5").Value = "3000"
' Apply styles to the chart.
With myChart
.ChartStyle = 4
.ApplyLayout 4
.ClearToMatchStyle
End With
' Add the axis title.
With myChart.Axes(xlValue)
.HasTitle = True
.AxisTitle.Text = "Units"
End With
'Add a new data series - TYPE MISMATCH ERROR!!!
myChart.SeriesCollection.NewSeries
myChart.SeriesCollection(2).Name = "New_Series"
myChart.SeriesCollection(2).Values = gWorkSheet.Range("C2:C5") 'Range that is in the worksheet
'myChart.ApplyDataLabels
' Clean up the references.
Set gWorkSheet = Nothing
' gWorkBook.Application.Quit
Set gWorkBook = Nothing
Set gChartData = Nothing
Set myChart = Nothing
End Sub
這個例子是在下面的鏈接:https://msdn.microsoft.com/en-us/library/office/ff973127(v=office.14).aspx
在爲了運行此代碼,需要導入:Visual Basic For Applications,Microsoft訪問對象庫,OLE自動化,Microsoft Office訪問數據庫引擎對象,Microsoft Office對象庫,Microsoft Powerpoint對象庫和Microsoft Excel對象庫。 (Powerpoint對象庫應先導入,然後再導入Microsoft Excel對象庫或存在引用問題)
您是否有任何關於如何添加新數據系列的想法或代碼中可能存在什麼問題?
非常感謝。
非常感謝的人!它工作,昨天我嘗試使用gworksheet.Range(..),價值但沒有工作,我不知道value2是關鍵,謝謝! – sahilu