为工作表中的所有列创建柱形图

时间:2013-12-06 05:54:11

标签: vba excel-vba excel

我需要为工作表中的所有列创建柱形图。对于前3列,代码运行良好,但从第4列开始,它显示无效的参数错误。我在代码中突出显示了错误以供参考。

Sub chart_builder()
'
' chart_builder Macro
'

'

For Count = 1 to 56

    ThisWorkbook.Worksheets("Sheet1").Activate
    Range(Cells(1, 1), Cells(233, Count + 1)).Select

    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xlColumnClustered
    ActiveChart.SetSourceData Source:=Range(Cells(1, 1), Cells(233, Count + 1))
    If Count <> 1 Then
        For j = 1 To Count - 1
            ActiveChart.SeriesCollection(j).Delete **"I am getting an invalid parameter error here**"
        Next
    End If
        ActiveChart.Parent.Cut
    Sheets.Add After:=Sheets(Sheets.Count)
    Range("B2").Select
    ActiveSheet.Paste
    ActiveSheet.Name = ThisWorkbook.Worksheets("Sheet1").Cells(1, Count + 1).Value

Next

End Sub

2 个答案:

答案 0 :(得分:0)

尝试使用此版本的内部循环(请参阅代码中的注释)

For j =( Count - 1) to 1 Step -1

    ActiveChart.SeriesCollection(j).Delete 'When deleting do it from last element to firest

Next

答案 1 :(得分:0)

我有相同的程序绘制工作表中的所有列并将其移动到新工作表中,并将标题作为工作表名称。
您可能想检查这是否适合您? 道歉,我很难调试你的代码。

Option Explicit
Sub Create_Chart()

Dim ws, wschart As Worksheet, ch As Chart, lrow, i As Long

Set ws = ThisWorkbook.Sheets("Source")

For i = 0 To 2 'this depends how many column you have which can also be made dynamic
    With ws
        lrow = .Range("A" & .Rows.Count).Offset(0, i).End(xlUp).Row
        Set ch = .Shapes.AddChart.Chart.Location(Where:=xlLocationAsNewSheet, Name:=.Range("A1").Offset(0, i).Value)
        ch.ChartType = xlColumnClustered
        ch.SetSourceData Source:=.Range("A1:A" & lrow).Offset(0, i)
        Set ch = Nothing
    End With
Next i

Set ws = nothing

End Sub

希望这能让你有更多的想法来实现你想要的目标。