0

我正在尝试制作一个宏,它将通过一个 Excel 表运行并通过一组行并为每一行制作一个图表。

我有一些代码可以满足我的需要,但是当我需要为每一行提供一个单独的图表时,将它们全部放在一个图表上。

`Dim i As Integer
 Dim ws As Worksheet
 Set ws = Sheets("Master Sheet")
 For Row = 1 To 20
 Dim my_cell
 Dim rng As Range
 Set rng = Sheets("Master Sheet").Range("J8:Y8")

 For Each my_cell In rng
 If my_cell <> "" Then

 ActiveSheet.Shapes.AddChart.Select
 ActiveChart.SetSourceData Source:=Range("'Master Sheet'!$J$8:$Y$8")
 ActiveChart.ChartType = xlLineMarkers
 ActiveChart.Location Where:=xlLocationAsNewSheet
 ActiveSheet.Activate
 ActiveChart.PlotArea.Select
 ActiveChart.SeriesCollection(1).XValues = "='Master Sheet'!$J$2:$Y$2"
 ActiveChart.SeriesCollection(1).Name = "=""FP"""
 ActiveChart.SeriesCollection.NewSeries
 ActiveChart.SeriesCollection(2).Name = "=""Progress"""
 ActiveChart.SeriesCollection(2).Values = _
 "='Master Sheet'!$J$8,'Master Sheet'!$AF$8:$AH$8"
 ActiveChart.DisplayBlanksAs = xlInterpolated
 ActiveSheet.Activate
 ActiveChart.ChartArea.Select

 Else
 Exit For ' Blank cell found, exiting
 End If
 Next

 Next Row
 End Sub` 

如果有人可以帮我看看我哪里出错了,那就太好了。

4

1 回答 1

2

不太确定您的For NextandFor Each循环结构是否良好。理想情况下,您希望逐步遍历范围并实际使用您在For Each语句中定义的值。在没有看到您的工作簿的情况下,我只是调整了一小部分数据来模拟创建图表。

我刚刚使用了相同的代码,并在同一个工作表上为每一行数字生成了一个图表。您可以将这些原则应用到您的逻辑中。

Sub test()
 Dim Row As Integer
 Dim ws As Worksheet
 Dim rng As Range

 Set ws = Sheets("Sheet1") 'Change this to: Set ws = Sheets("Master Sheet")

 For Row = 1 To 6
 Set rng = ws.Range("B1:D1").Offset(Row, 0) 'Change to (I'm guessing here): ws.Range("$J$7:$Y$7").Offset(Row, 0)

 ActiveSheet.Shapes.AddChart.Select
 ActiveChart.SetSourceData Source:=Range(ws.Name & "!" & rng.Address)
 ActiveChart.ChartType = xlLineMarkers
 ActiveChart.PlotArea.Select
 ActiveChart.SeriesCollection(1).XValues = "='Sheet1'!$B$1:$D$1" 'Change to "='Master Sheet'!$J$2:$Y$2"
 ActiveChart.SeriesCollection(1).Name = ws.Range("A1").Offset(Row, 0).Value 'Change this to whatever you want to name the graphs. This is currently set to dynamicly name each graph by the series name set in Column A.
 'ActiveChart.Location Where:=xlLocationAsNewSheet 'uncomment this line to put on new sheet
 'ws.Select 'Need to go back to worksheet

 Next Row

 Set ws = nothing
 Set rng = nothing
End Sub

这里有几个链接可能会有所帮助; 在 for 循环 VBA和 Excel VBA中创建和定位图形:将循环通过唯一名称组并创建相应图表的图表制作宏?

谷歌还有许多其他链接。

如果我误解了您的问题或需要其他任何内容,请告诉我。

干杯

于 2012-10-16T00:02:13.783 回答