Forum Discussion
Excel recorded macro to VBA to call from a different software
Hello Junsh-
Please try the below code. See attached workbook for reference:
Note: I have named the charts in order... myCht1, myCht2, myCht3 .....
Sub WorksheetLoop2() ' Declare Current as a worksheet object variable. Dim Current As Worksheet Dim intLp As Integer ' Loop through all of the worksheets in the active workbook. For Each Current In Worksheets 'ActiveSheet.Shapes.Range("myCht" & intLp + 1).Select Current.ChartObjects("myCht" & intLp + 1).Activate With ActiveChart .ChartType = xlColumnClustered .SetSourceData Source:=Range("B5:M5") .SeriesCollection(1).XValues = "=Current!B$1:$M$2" .SeriesCollection(1).Select .PlotArea.Select .SeriesCollection(1).Select .SeriesCollection(1).ApplyDataLabels .SeriesCollection(1).DataLabels.Select .SeriesCollection(1).Select End With intLp = intLp + 1 'MsgBox Current.Name Next End Sub
- Matt MickleJun 28, 2018Bronze Contributor
Sorry I must have forgot to attach the workbook. See previous post. You have to rename the charts for it to work properly. Select the chart then change the name in the upper left hand corner. They need to be in the order the sheets are in...
- junsh.graceJun 29, 2018Copper ContributorSorry to bother you again Matt. I tried running the macro on a different computer to see if there was something wrong with my workstation but ended up with the same error. Wouldn't you incorporate chart naming in the macro? I suppose the error message is prompted because there are no chart name "myCht1", "myCht2", etc. Did you name your chart manually before running the macro? Another question: why did you comment out the first line after the for loop line? 'ActiveSheet.Shapes.Range("myCht" & intLp + 1).Select Thanks! Junsh
- Matt MickleJun 29, 2018Bronze Contributor
I did name them manually before hand. I wasn't sure if you had more than one chart on each worksheet. So I wanted to make sure I could name them based on an easy convention. This also prevents the need to cycle through all of the shapes in the workbook looking for the chart.
The line I commented out was done so because it serves no purpose. I was fiddling around testing how to work with charts, because it's been a while and during the testing I determined this wasn't necessary.
I could incorporate naming the chart in the file you are correct. I just wanted the most direct way to access the chart objects without having to cycle thorough any others....