需要使用vba宏循环在excel中创建一组图形

时间:2012-10-15 22:47:52

标签: excel vba loops graph

我正在尝试创建一个宏,它将遍历一个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` 

如果有人能帮我看看我出错的地方会很棒。

1 个答案:

答案 0 :(得分:2)

不确定您是否已经很好地构建了For NextFor 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

以下是一些可能有用的链接; Creating and positioning graphs in a for loop VBAExcel VBA: Chart-making macro that will loop through unique name groups and create corresponding charts?

Google还有许多其他链接。

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

干杯