将零添加到图表数据源

我想将数字(0)添加到值,并find一些麻烦。 以这个macroslogging为例

Sub Makro2() ActiveSheet.ChartObjects("Chart 1").Activate ActiveChart.SeriesCollection.NewSeries ActiveChart.SeriesCollection(2).XValues = _ "='Sheet'!$C$221;'Sheet'!$C$223;'Sheet'!$C$225" ActiveChart.SeriesCollection(2).Values = _ "='Sheet'!$B$222;'Sheet'!$B$224;'Sheet'!$B$226" End Sub 

但是,当我尝试与我的代码相同,我得到错误。

 Dim lineSeries1 As Range Dim lineSeries2 As Range With ActiveChart.SeriesCollection.NewSeries .Values = "={0;100}" 'It works .Name = "" .XValues = "={0;100}" 'It works End With With ActiveChart.SeriesCollection.NewSeries .Values = lineSeries1 ' + {0} or & SomeCellWithZero.Address .Name = "" .XValues = lineSeries2 ' + {0} or & SomeCellWithZero.Address End With 

所以问题是如何将零值添加到值?

就个人而言,我会使我的范围变大一个单元格,并添加一个恒定的零值。 如果由于某种原因,这是不可能的,接下来可能会有所帮助;-)

这是一个稍微迂回的方式去那里。 有可能用更less的步骤做到这一点,但我现在还看不到。

我将使用VBA函数从原始范围构build一个包含零的新数组。 我在数组的开始放零,改变代码的东西不同。 这是VBAfunction:

 Public Function PrependZero(rng As range) Dim val As Variant, res As Variant Dim idx As Long val = Application.Transpose(rng.Columns(1).Value) ' get range values as a 1-dimensional array, assumes values are in a column ReDim res(LBound(val) To UBound(val) + 1) ' array to hold the extended values res(LBound(res)) = 0 ' add the fixed value For idx = LBound(val) To UBound(val) res(idx + 1) = val(idx) ' copy the other values Next PrependZero = res End Function 

Excel似乎并不喜欢我们在一个系列定义中使用VBA函数,所以我们需要添加一些间接来愚弄它。 创build一个新的命名公式(公式…定义名称)。 我调用了我的YSeries ,并将“指向”值设置为=PrependZero(Sheet1!$A$2:$A$6) ,使用我的Y值范围作为函数的input。

该命名公式用于图表系列定义:将“Series Y Values”设置为[YourWorkbookNameHere]!YSeries (使用上面创build的任何名称)。

如果你想对X值做同样的处理,也应该使用相同的方法。