Excel 将零添加到图表数据源

Excel 将零添加到图表数据源,excel,vba,Excel,Vba,我想将数字(0)添加到值中,并发现有点问题。将此宏记录为 Sub Makro2() ActiveSheet.ChartObjects("Chart 1").Activate ActiveChart.SeriesCollection.NewSeries ActiveChart.SeriesCollection(2).XValues = _ "='Sheet'!$C$221;'Sheet'!$C$223;'Sheet'!$C$225" ActiveCh

我想将数字(0)添加到值中,并发现有点问题。将此宏记录为

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

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

就我个人而言,我会将量程增大一个单元格,然后加上一个恒定的零值。如果由于某种原因无法实现,下面的内容可能会有所帮助;-)

这里有一条稍微绕道去那里的路。也许用更少的步骤就可以做到这一点,但我还不知道怎么做

我将使用VBA函数从原始范围构建一个包含零的新数组。我把零放在数组的开头,更改代码以获得不同的结果。以下是VBA函数:

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函数,所以我们需要添加一些间接操作来愚弄它。创建新的命名公式(公式…定义名称)。我调用了我的
YSeries
,并使用Y值范围作为函数的输入,将“reference-to”值设置为
=PrependZero(Sheet1!$A$2:$A$6)

该命名公式可用于图表系列定义:将“系列Y值”设置为
[YourWorkBookName here]!YSeries
(使用您在上面创建的任何名称)

如果您希望对X值执行相同的操作,则应使用相同的方法