更新:循环几个范围?

时间:2016-03-02 03:31:58

标签: excel vba excel-vba loops range

更新:我稍微修改了Nick建议的代码。最初,这个带有Rng.Offset的代码获取了大范围的数据来制作雷达图。例如:从(A1:E1):( A2:E2)(这首先是好的),但随后它去了:(A1:E1):( A3:E3),(A1:E1):( A4:E4) ,(A1:E1):( A5:E5),等等......我试图每次只选择一行,因此:(A1:E1)+(A3:E3),(A1:E1) )+(A4:E4),(A1:E1)+(A5:E5)。

Sub MultipleRadarCharts()

Dim i As Integer
Dim Rng As Range

Set Rng = Sheets("Indices4Pilares (4)").Range("A1:E1")

For i = 2 To 36
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xlRadarMarkers
   'ActiveChart.SetSourceData Source:=Sheets("Indices4Pilares (4)").Range(Rng, Rng.Offset(i - 1, 0))
   'ActiveChart.SetSourceData Source:=Sheets("Indices4Pilares (4)").Range(Rng, Range(Cells(i, 1), Cells(i, 5)))
    ActiveChart.SetSourceData Source:=Sheets("Indices4Pilares (4)").Union(Range(Cells(1, 1), Cells(1, 5)), Range(Cells(i, 1), Cells(i, 5))).Select
    ActiveChart.Legend.Delete
Next i
Set Rng = Nothing
End Sub

=====

:)我刚刚创建了这段代码,以便从Excel表格中获取雷达图表。

第一行有变量的名称,然后(从第2行到第36行)有值。问题是我试图用“for循环”来简化代码,但我无法使其工作:(

这是我想简化的原始代码......

Sub Macro2()

Range("A1:E1,A2:E2").Select
Range("A2").Activate
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlRadarMarkers
ActiveChart.SetSourceData Source:=Range( _
    "'Indices4Pilares (3)'!$A$1:$E$1,'Indices4Pilares (3)'!$A$2:$E$2")
ActiveChart.Legend.Select
Selection.Delete

Range("A1:E1,A3:E3").Select
Range("A3").Activate
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlRadarMarkers
ActiveChart.SetSourceData Source:=Range( _
    "'Indices4Pilares (3)'!$A$1:$E$1,'Indices4Pilares (3)'!$A$3:$E$3")
ActiveChart.Legend.Select
Selection.Delete

Range("A1:E1,A4:E4").Select
Range("A4").Activate
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlRadarMarkers
ActiveChart.SetSourceData Source:=Range( _
    "'Indices4Pilares (3)'!$A$1:$E$1,'Indices4Pilares (3)'!$A$4:$E$4")
ActiveChart.Legend.Select
Selection.Delete

Range("A1:E1,A5:E5").Select
Range("A5").Activate
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlRadarMarkers
ActiveChart.SetSourceData Source:=Range( _
    "'Indices4Pilares (3)'!$A$1:$E$1,'Indices4Pilares (3)'!$A$5:$E$5")
ActiveChart.Legend.Select
Selection.Delete
End Sub

1 个答案:

答案 0 :(得分:1)

请尝试以下代码:

Sub MultipleRadarCharts()

Dim i As Integer
Dim Cht As Chart
Dim Rng As Range

Set Rng = Sheets("Indices4Pilares (3)").Range("A1:E1")

For i = 2 To 36
    Set Cht = ActiveSheet.Shapes.AddChart
    Cht.ChartType = xlRadarMarkers
    'Cht.SetSourceData Source:=Sheets("Indices4Pilares (3)").Range(Rng, Rng.Offset(0, i - 1)) 'Old solution
    Cht.SetSourceData Source:=Sheets("Indices4Pilares (3)").Range(""Rng.Address & "," & Rng.Offset(0, i - 1).Address"") 'New solution
    Cht.Legend.Delete
    Set Cht = Nothing
Next i

Set Rng = Nothing

End Sub