循环遍历excel表并创建图形

时间:2018-05-11 16:53:36

标签: excel vba excel-vba

我在一个工作表中有多个表,我需要遍历表(列表对象)并生成相应的线图。我尝试使用每个循环,它不起作用: 如何为每个'使用'循环生成图形?如何将每个列表对象作为我的图形的范围引用?

Sub chart_create()

Dim tbl As listobject

'Loop through each sheet and table in the workbook

    For Each tbl In ActiveSheet.ListObjects         
     Call graph
  End Sub

    Next tbl

End Sub

'macro to generate charts 

Sub graph()

    Dim rng As Range
    Dim cht As ChartObject
 'how do i change this to reference corresponding list object 
    Set rng = Selection   

    Set cht = ActiveSheet.ChartObjects.Add( _
        Left:=ActiveCell.Left, _
        Width:=450, _
        Top:=ActiveCell.Top, _
        Height:=250)

    'Give chart some data
    cht.Chart.SetSourceData Source:=rng

    'Determine the chart type
    cht.Chart.ChartType = xlLine

End Sub

2 个答案:

答案 0 :(得分:1)

将ListObject的Range作为参数传递到第二个子例程中:

Sub chart_create()

  Dim tbl As listobject

  'Loop through each sheet and table in the workbook
  For Each tbl In ActiveSheet.ListObjects         
     Call graph tbl.Range
  Next tbl

End Sub

'macro to generate charts
Sub graph(rng as range)     
    Dim cht As ChartObject

    Set cht = ActiveSheet.ChartObjects.Add( _
        Left:=ActiveCell.Left, _
        Width:=450, _
        Top:=ActiveCell.Top, _
        Height:=250)

    'Give chart some data
    cht.Chart.SetSourceData Source:=rng

    'Determine the chart type
    cht.Chart.ChartType = xlLine

End Sub

答案 1 :(得分:1)

首先,看起来你还有一个额外的End Sub。 <{1}}必须在Next tbl之前,否则永远不会到达。

其次,您需要将对表的引用传递给图形函数。

End Sub

然后......

Sub chart_create()

    Dim tbl As listobject

    'Loop through each sheet and table in the workbook

    For Each tbl In ActiveSheet.ListObjects         
        Call graph(tbl)
    Next tbl
End Sub

编辑:最后,为了清楚起见,您的评论说您“循环遍历工作簿中的每个工作表和表格”,但实际上您只是在活动工作表上循环浏览listobjects。如果你想循环遍历每个工作表,你需要在现有循环之外有一个额外的循环,如:

Sub graph(tbl As ListObject)
    'Make your graph here, referencing the tbl you passed in
End Sub