List(Of Decimal)
是否可以使用 VB 从 Excel 中的值创建绘图?我想避免将数据直接转储到表格中,然后从中创建图表。到目前为止,这是我所拥有的,但是当我尝试分配.XValues
和分配.Values
给列表时,我遇到了数据类型不匹配的问题。是否需要进行某种转换才能将列表转换为系列?
Dim Series As Excel.Series
Dim xVals As New List(Of Decimal)(New Decimal() {1, 3, 4, 5})
Dim yVals As New List(Of Decimal)(New Decimal() {2, 2, 2, 2})
xlWorkSheet = CType(Globals.ThisAddIn.Application.Worksheets.Add(), Excel.Worksheet)
xlWorkSheet.Activate()
xlWorkSheet.Name = "My Sheet"
xlCharts = xlWorkSheet.ChartObjects
xlChartObj = xlCharts.Add(150, 30, 400, 250)
xlChart = xlChartObj.Chart
With xlChart
.ChartType = Excel.XlChartType.xlXYScatterLines
.HasLegend = True
.Legend.Position = Excel.XlLegendPosition.xlLegendPositionRight
.HasTitle = True
.ChartTitle.Text = "Test Chart"
For i = 0 To channels.Count - 1
.SeriesCollection.NewSeries()
Series = .SeriesCollection(i + 1)
Series.XValues = xVals
Series.Values = yvals
Next
.Location(Excel.XlChartLocation.xlLocationAsNewSheet)
End With
更新:
我似乎下面的代码可以工作,但它不是很理想。除了像我一样将数组转换为数组的字符串表示形式之外,还有更好的方法吗?
Dim Series As Excel.Series
Dim xVals As New List(Of Decimal)(New Decimal() {1, 3, 4, 5})
Dim yVals As New List(Of Decimal)(New Decimal() {2, 2, 2, 2})
Dim xString As String
Dim yString As String
xlWorkSheet = CType(Globals.ThisAddIn.Application.Worksheets.Add(), Excel.Worksheet)
xlWorkSheet.Activate()
xlWorkSheet.Name = "My Sheet"
xlCharts = xlWorkSheet.ChartObjects
xlChartObj = xlCharts.Add(150, 30, 400, 250)
xlChart = xlChartObj.Chart
With xlChart
.ChartType = Excel.XlChartType.xlXYScatterLines
.HasLegend = True
.Legend.Position = Excel.XlLegendPosition.xlLegendPositionRight
.HasTitle = True
.ChartTitle.Text = "Test Chart"
For i = 0 To channels.Count - 1
.SeriesCollection.NewSeries()
Series = .SeriesCollection(i + 1)
xString = "={"
xString += xVals(0).ToString
For k = 1 To xVals.Count - 1
xString += ","
xString += xVals(k).ToString
Next
xString = "}"
yString = "={"
yString += yVals(0).ToString
For k = 1 To yVals.Count - 1
yString += ","
yString += yVals(k).ToString
Next
yString = "}"
Series.XValues = xString
Series.Values = yString
Next
.Location(Excel.XlChartLocation.xlLocationAsNewSheet)
End With