Excel - Macro to create chart based on selection

2019-07-24 19:02发布

问题:

I would like to ask for your help concerning the following issue: For I have to create a large numbers of charts, I would like to have a macro which would insert the chart based on my selection. As I do not have any clue about VBA but need it now (as for now, at least - I really should learn to use it on my own), I would appreciate your help. Basically, I need to know how to adjust the code I recorded, such that the chart will be inserted based on my selection:

Sub chartmacro()
    ActiveCell.Range("A1:E2").Select
    ActiveSheet.Shapes.AddChart2(240, xlXYScatter).Select
    ActiveChart.SetSourceData Source:=Range("Tabelle1!$A$1:$E$2")
End Sub

I do not know, how to change the values in the "Range"-statement, such that they refer to my selection.

I would be glad, if you could consider my question.

Yours sincerely, Sinistrum

回答1:

This is what I can do for you. You can go further from here.

Option Explicit

Sub Charter()

    Dim my_range    As Range

    Set my_range = Selection
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xlColumnClustered
    ActiveChart.SetSourceData Source:=my_range

    Cells(1, 1).Select

End Sub

Next steps - declare the chart as variable, remove the selections, etc. But the code works ok.



标签: excel vba charts