如何用vba在工作表中新建图表?

用vba在工作表中新建图表的方法有很多种。

一、用Shapes对象的AddChart方法(该方法已经被作废,但是仍然可以使用)

代码如下:

Sub exceloffice()
    '作者QQ:1722187970,微信:xycgenius,微信公众号exceloffice
    Dim oChart As Chart
    Dim oSP As Shape
    Dim oWK As Worksheet
    Set oWK = Excel.ActiveSheet
    With oWK
        If .ChartObjects.Count > 0 Then
            '先删除所有图表
            .ChartObjects.Delete
        End If
        Set oSP = .Shapes.AddChart(xlColumnClustered, 0, 0, 300, 300)
        Set oChart = oSP.Chart
        With oChart
            .SetSourceData oWK.Range("A1").CurrentRegion
        End With
    End With
End Sub

二、用Shapes对象的AddChart2方法

代码如下:

Sub exceloffice()
    '作者QQ:1722187970,微信:xycgenius,微信公众号exceloffice
    Dim oChart As Chart
    Dim oSP As Shape
    Dim oWK As Worksheet
    Set oWK = Excel.ActiveSheet
    With oWK
        If .ChartObjects.Count > 0 Then
            '先删除所有图表
            .ChartObjects.Delete
        End If
        '相比AddChart新增2个参数,第一个参数指定用哪个图表样式,最后一个参数表示是否显示图表标题和图例
        Set oSP = .Shapes.AddChart2(-1, xlColumnClustered, 0, 0, 300, 300, True)
        Set oChart = oSP.Chart
        With oChart
            .SetSourceData oWK.Range("A1").CurrentRegion
        End With
    End With
End Sub

三、用ChartObjects对象的Add方法

代码如下:

Sub exceloffice()
    '作者QQ:1722187970,微信:xycgenius,微信公众号exceloffice
    Dim oChart As Chart
    Dim oChartObject As ChartObject
    Dim oWK As Worksheet
    Set oWK = Excel.ActiveSheet
    With oWK
        If .ChartObjects.Count > 0 Then
            '先删除所有图表
            .ChartObjects.Delete
        End If
        Set oChartObject = .ChartObjects.Add(0, 0, 200, 200)
        Set oChart = oChartObject.Chart
        With oChart
            .SetSourceData oWK.Range("A1").CurrentRegion
        End With
    End With
End Sub

其中ChartObjects对象的Add方法和Shapes对象的AddChart方法基本相同,都是先创建一个图表容器,设置好图表的位置和大小。

       

发表评论