gpt4 book ai didi

vba - Excel 中的多个图表

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

我正在进行研究,我必须为每张工作表生成超过 91 个图表,我想使用宏来做到这一点。

我仍然是宏的新手,但我试图写这个,但它不起作用。非常感谢您在这个问题上的帮助!

我拥有的数据集如下所示

> A1         B1     C1    D1    E1     F1    G1       H1    I1
>
>
> Period Ratio Period Ratio Period ratio
> 2000Q1 1.23 2000Q1 0.78 2000Q1 1.07
> 2000Q2 1.43 2000Q2 1.12 2000Q2 0.76 2000Q3 1.8
> 2000Q3 1.09 2000Q3 1.21

(在 A 列和 B 列下我有周期和比率) - 然后 C 列是空的 - 然后(在 D 和 E 列下我有周期和比率)等等。

我用一个空列分隔数据集。

请注意,还有其他行(我有一个更新按钮,每次单击带有(周期比率)的新行时,都会为所有列添加) - 第一行的值也从第 3 行开始

我想为每组数据创建一个图表(这里是 3 个图表)

我写的宏如下:
Sub loopChart()
Dim mychart As Chart
Dim c As Integer
Sheets("analysis").Select

c = 1
While c <> 0 #I put this condition so that the code will know that I have no more data set

Set mychart = Charts.Add
mychart.SetSourceData Source:=Range(cells(3, c)).CurrentRegion, PlotBy:=xlColumns
c = c + 3
Wend

For Each mychart In Sheets("class").ChartObjects
mychart.ChartType = xlLineMarkers
Next mychart

End Sub

我不太确定我在做什么是正确的,但我面临着范围的问题。我也知道这个宏会创建一个新的图表。

如何在值旁边的“分析”表上创建所有图表?

我将非常感谢任何人的帮助!

最佳答案

我的 friend 。工作簿可以直接包含图表,也可以将图表集成到工作表中。这取决于你想要什么。 Excel 是一个面向对象的程序。 Range.CurrentRegion应该可以,但是如果周围有任何填充的单元格,则可能会导致问题。

尝试这个 :

Sub loopChart()

Dim mychart As Chart
Dim myRange As range
Dim c As Integer
c = 1

While c <= 7 '1=dataSource1, 4=dataSource2, 7=dataSource3
'set data source for the next chart
With Worksheets("class")
Set myRange = .range(.Cells(3, c), .Cells(6, c + 1))
End With

'create chart
Sheets("analysis").Select
ActiveSheet.Shapes.AddChart.Select

With ActiveChart
.ChartType = xlLineMarkers 'xlLine
.SetSourceData Source:=myRange, PlotBy:=xlColumns 'sets source data for graph including labels
.SetElement (msoElementLegendRight) 'including legend
.HasTitle = True
'dimentions & location:
.Parent.Top = 244 'defines the coordinates of the top of the chart
.Parent.Left = c * 100 'defines the coordinates for the left side of the chart
.Parent.Height = 200
.Parent.Width = 300
.ChartTitle.Text = "Title here"
End With

c = c + 3
Wend

End Sub

结果 :
Screenshot

如需更多案例,您可以访问 Microsoft Office 开发中心:
Creating Charts in Excel 2003 Using Visual Basic for Applications Code

关于vba - Excel 中的多个图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30968381/

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