Forum Discussion
junsh.grace
Jun 27, 2018Copper Contributor
Excel recorded macro to VBA to call from a different software
Hello, I have no functional knowledge of VBA but needs to call a VBA from a different software (namely SAS) to create chart on multiple excel worksheets with specific formats. I've recorded a...
Matt Mickle
Jun 28, 2018Bronze Contributor
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
- junsh.graceJun 28, 2018Copper ContributorThank you Matt for your help. I almost gave up and though about recording a macro for all 13 sheets I n Unfortunately, the line of code, Current.ChartObjects("myCht" & intLp + 1).Activate had a run-time error, "The item with the specified name wasn't found". Would you please attach the file that worked for you? I guess there are numerous ways to go about looping a macro through all worksheets. At one point, my existing codes worked for referencing the correct data on each sheet, but when I tried my code again, it didn't behave quite as expected (i.e. generating three graphs on the first sheet with the wrong data). Any of your help is greatly appreciated! Junsh
- 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