使用具有嵌入式公式的命名范围用于Excel图表数据

时间:2018-05-16 22:55:38

标签: excel vba excel-vba named-ranges

我有两个下拉菜单,列出了一系列日期。一个日期标识范围的开始,另一个日期标识结束。我还创建了两个命名范围,如下所示:

chart_Dates=INDEX(Dates,MATCH(Home!$A$7,Dates,0)):INDEX(Dates,MATCH(Home!$A$9,Dates,0))
chart_Frequency=INDEX(Frequency,MATCH(Home!$A$7,Dates,0)):INDEX(Frequency,MATCH(Home!$A$9,Dates,0))
来自这些公式的

DatesFrequency是具有设置边界的命名范围。如果我手动输入y值为“Home!chart_Frequency”,水平值为Home!chart_Dates,则宏工作正常。我可以使用下拉菜单调整开始日期和结束日期,并相应地更新图表。

但是,宏录制器不会将这些操作转换为代码。我尝试了以下代码但未成功(没有生成错误,但图表仅引用了我的范围中的第一个单元格)。

ActiveChart.SeriesCollection(1).Values = Range("chart_Frequency")
ActiveChart.SeriesCollection(1).XValues = Range("chart_Dates")

如何让代码复制我手动执行的操作?非常感谢任何建议!

2 个答案:

答案 0 :(得分:0)

试试这个:

Sub testing()
    Dim freqRange As String
    Dim datesRange As String
    Dim Name As Variant
    For Each Name In ThisWorkbook.Names
        If Name.Name = "chart_Frequency" Then
            freqRange = Name.Value
        ElseIf Name.Name = "chart_Dates" Then
            datesRange = Name.Value
        End If
    Next Name
    ActiveSheet.ChartObjects("Chart 1").Activate
    ActiveChart.SeriesCollection.NewSeries
    ActiveChart.FullSeriesCollection(1).Name = "=Sheet1!$B$1"
    ActiveChart.FullSeriesCollection(1).Values = datesRange
    ActiveChart.FullSeriesCollection(1).XValues = freqRange
End Sub

我的图表没有任何系列,因此它添加了一个新系列,它更新了名称,值和XValues,没有任何问题。

答案 1 :(得分:0)

这是我现在的代码。运行后,当我检查图表本身的y值和水平值时,它们都是空白的。

'Create chart
Dim rng As Range
Dim cht As ChartObject

'Data range for the chart
Set rng = ActiveSheet.Range("$E$7:$F$501")

'Designates which cell to place the top left corner of the graph in
ActiveSheet.Range("N5").Select

'Create a chart
Set cht = ActiveSheet.ChartObjects.Add( _
Left:=ActiveCell.Left, _
Width:=360, _
Top:=ActiveCell.Top, _
Height:=216)

'Give chart some data
'I was using the line below to set the range but comment blocked it out and entered the suggested code
'  cht.Chart.SetSourceData Source:=rng
Dim freqRange As String
Dim datesRange As String
Dim Name As Variant
For Each Name In ThisWorkbook.Names
    If Name.Name = "chart_Frequency" Then
        freqRange = Name.Value
    ElseIf Name.Name = "chart_Dates" Then
        datesRange = Name.Value
    End If
Next Name
ActiveSheet.ChartObjects("Chart 1").Activate
ActiveChart.SeriesCollection.NewSeries
ActiveChart.FullSeriesCollection(1).Name = "=Home!$A$5"
ActiveChart.FullSeriesCollection(1).Values = datesRange
ActiveChart.FullSeriesCollection(1).XValues = freqRange

'Determine the chart type
cht.Chart.ChartType = xlLineMarkersStacked

'Remove Major Gridlines
cht.Chart.Axes(xlValue).MajorGridlines.Delete

'Sets the legend to the bottom of the graph
cht.Chart.SetElement (msoElementLegendBottom)
cht.Name = "Frequency_Chart"

'Add title and reference A5 for name
ActiveSheet.ChartObjects("Frequency_Chart").Activate
ActiveChart.SetElement (msoElementChartTitleAboveChart)
Application.CutCopyMode = False
Selection.Caption = "=Home!R5C1"