gpt4 book ai didi

vba - 如何使用 VBA 为 excel 图表分配 XValues

转载 作者:行者123 更新时间:2023-12-04 19:53:28 25 4
gpt4 key购买 nike

我有这个 VBA 函数用于在 Excel 2013 中绘制图表:

Sub DrawChart2(obj_worksheetTgt As Worksheet, ByVal XLabels As Range, ByVal DataValues As Range, ByVal chartTitle As String, a As Integer, b As Integer)
'
'obj_worksheetTgt - Object worksheet on which to be placed the chart
'XLabels - Data range for X labels
'DataValues - Data range for Y values
'chartTitle - Chart title
'a - left border position of chart in pixels
'b - top border position of chart in pixels


With obj_worksheetTgt.ChartObjects.Add(a, b, 900, 300) ' Left, Top, Width, Height
With .Chart
.ChartType = xlBarClustered
Set .SeriesCollection(1).XValues = XLabels ' Here is the error
Set .SeriesCollection(1).Values = DataValues
.Legend.Position = -4107
.HasTitle = True
.chartTitle.Text = chartTitle
.chartTitle.Font.Size = 12
With .Axes(1).TickLabels
.Font.Size = 8
.Orientation = 90
End With
End With
End With
End Sub

我这样调用函数:

ChartsWorksheet = "Summary"
Queryname = "query1"
chartTitle = "Values"
With .Worksheets("LastDayData").ListObjects(Queryname)
Set chart_labels = .ListColumns(2).DataBodyRange
Set chart_values = .ListColumns(6).DataBodyRange
End With
Call DrawChart2(.Worksheets(ChartsWorksheet), chart_labels, chart_values, chartTitle, 10, 10)

我收到一个错误:

Runtime Error '1004':

Invalid Parameter

当我单击调试时,它会在上面的函数中标记行“Set .SeriesCollection(1).XValues = XLabels”。

在文档中写到:

The XValues property can be set to a range on a worksheet or to an array of values, but it cannot be a combination of both

所以它应该能够将给定的范围作为XValues的值,但我不明白为什么会出现这个错误。

最佳答案

在设置系列的值和 X 值之前,您需要先添加系列。使用 SeriesCollection.NewSeries 方法很简单,如下所示:

With ActiveSheet.ChartObjects.Add(a, b, 900, 300) ' Left, Top, Width, Height
With .Chart
.ChartType = xlBarClustered

' need to add the series before you can assign the values/xvalues
' calling the "NewSeries" method add one series each time you call it.

.SeriesCollection.NewSeries

' now that the series is added, you may assign (not set) the values/xvalues

.SeriesCollection(1).XValues = XLabels
.SeriesCollection(1).Values = DataValues
End With
End With

关于vba - 如何使用 VBA 为 excel 图表分配 XValues,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27821680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com