Search code examples
vbaexcelexcel-2010excel-2013

Create Temporary Excel Chart


Sub aaGraphing()
'
' aaGraphing Macro
'

'
    Range("L948:W949,D948:D949").Select
    Range("D949").Activate
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xlLineMarkers
    ActiveChart.SetSourceData Source:=Range( _
        "Analytics!$L$948:$W$949,Analytics!$D$948:$D$949")
End Sub

This code creates a chart of the data I want. Is there a way to way to make the created chart temporary so that when you click anywhere outside of the chart it deletes?


Solution

  • Regular module....

    Option Explicit
    
    
    Public PlotName As String
    Public PlotRange As Range
    
    
    Sub Tester()
    AddPlot ActiveSheet.Range("B3:B7,D3:D7")
    End Sub
    
    Sub AddPlot(rng As Range)
        With ActiveSheet.Shapes.AddChart
            PlotName = .Name
            .Chart.ChartType = xlLineMarkers
            .Chart.SetSourceData Source:=Range(rng.Address())
        End With
        Set PlotRange = rng
        Application.EnableEvents=False    
        rng.Select
        Application.EnableEvents=True
    End Sub
    
    Sub RemovePlot(rng As Range)
        If Not PlotRange Is Nothing Then
            If Application.Intersect(rng, PlotRange) Is Nothing Then
                On Error Resume Next
                rng.Parent.Shapes(PlotName).Delete
                On Error GoTo 0
            End If
        End If
    End Sub
    

    Sheet code module:

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        RemovePlot Target
    End Sub