循环通过工作表在VBA

时间:2017-01-26 09:36:39

标签: excel vba excel-vba charts

我正在尝试根据工作表中的某些数据创建图表。我有一个创建图表的代码。

问题 我正在尝试遍历工作簿中的工作表,以检查图形是否已经存在,在这种情况下,我将其激活,清理以前的数据并将新数据放入。

如果不是,我创建一个新图并将数据放入。

我尝试创建一个双循环来检查工作表的名称是否匹配,但这不起作用(无法将图表设置为空)。

关于该怎么做的任何想法?

当前代码(仅限相关部分)

Set RetRange = w.Sheets("Ret").UsedRange
  ' Set RetRange = w.Sheets("Returns Output").Range(w.Sheets("Ret").Cells("A1").SpecialCells(xlLastCell))

'if graph is already there, change       
Set RetChart = Nothing

For Each ws In w.Worksheets
    If ws.Name = "RetGraph" Then         
        Set RetChart = Charts("Ret").Activate    
    Else

    End If
Next ws

If RetChart = Nothing Then
    Set RetChart = Charts.Add        
End If

With RetChart
    .Select                
    .ChartType = xlLine                
    .HasTitle = True
    .ChartTitle.Text = "Index Performance"
    .SetSourceData Source:=RetRange
    .Axes(xlCategory, xlPrimary).HasTitle = True
    .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Date"
    .Axes(xlValue, xlPrimary).HasTitle = True
    .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Return"
    .Name = "RetGraph"
    .Legend.Select
     Selection.position = xlBottom
End With

End Sub

2 个答案:

答案 0 :(得分:0)

Name" Ret"是ChartObject的属性,而不是Chart

最高层级是ChartObject,您可以在其下方找到ChartName和其他许多层次结构,请参见下面的简短图表:

ChartObject
--> Chart
  |--> ChartArea
  |--> Axes
  |--> SeriesCollection
     |--> Format.Line
--> Name
--> Top 
--> Left  
--> Height
--> Width

评论:我建议您使用ChartObject,然后您可以轻松地在下面嵌套以修改所有其他属性。此外,几乎总是没有理由使用SelectSelection,但它是完全限定的ChartObjects及其嵌套属性。

下面的代码将遍历所有Worksheets,然后每个Worksheet将遍历所有ChartObjects,并搜索" Ret"。

<强>代码

Option Explicit

Sub LoopSheets_ChartObjects()

Dim RetChart As Chart
Dim ChtObj As ChartObject
Dim ws As Worksheet
Dim w As Workbook

Set w = ThisWorkbook

For Each ws In w.Worksheets
    If ws.Name = "RetGraph" Then
        For Each ChtObj In ws.ChartObjects
            If ChtObj.Name = "Ret" Then '<-- if there is a match
                Set RetChart = ChtObj.Chart ' <-- set chart to ChartObject.Chart
            End If
        Next ChtObj
    End If
 Next ws

If RetChart Is Nothing Then
    MsgBox "NOT Found"
    ' do your coding stuff
End If

End Sub

编辑1 :为了支持PO新信息,图表放在图表中。

Dim RetChart As Chart
Dim Cht_Sht As Chart

For Each Cht_Sht In w.Charts
    If Cht_Sht.Name = "RetGraph" Then
        Set RetChart = Cht_Sht
    End If
Next Cht_Sht

If RetChart Is Nothing Then
    MsgBox "NOT Found"
    ' do your coding stuff

Else ' <-- chart found
    RetChart.ChartTitle.Text = "Test" '<-- for debug only
End If

答案 1 :(得分:0)

你可以避免循环播放表格

Dim RetChart As Chart

On Error Resume Next
Set RetChart = w.Charts("RetGraph")
On Error GoTo 0

If RetChart Is Nothing Then '<--| chart not found
    MsgBox "NOT Found"
    ' do your coding stuff
Else ' <--| chart found
    RetChart.ChartTitle.Text = "Test" '<-- for debug only
End If
相关问题