VBA Excel 2010 - Assign unknown chart to varible - vba

Im trying to set a chart to a varible, however since I have multiple charts in my spreadsheet I need to be able to activate a chart and assign it to a varible.
Ffor the record ChartHandel = ActiveSheet.ChartObject(1) doesn't work,I have also tried .Shape(1) and Chart("Name of chart") and these too dont work
Dim ChartHandel2 As Chart
ActiveSheet.ChartObjects(1).Activate
ChartHandel2 = ActiveChart
Even this gets error '91, Object Variable or with block varible not set' which it looks like it should work and I was sure I had had this working at one point(as a workaround)
My question is basicly can you assign a chart to a varible if it isnt active (and if possible how)?

when assigning object you must use the Set keyword in the left part of the assignment statement
furthemore Chart object is a member of the ChartObject object
here's a small example of dealing with them
Option Explicit
Sub ChartObjects()
Dim chartObj As ChartObject
With ThisWorkbook.Worksheets("charts")
For Each chartObj In .ChartObjects
With chartObj ' to deal with current "ChartObject" object
With .Chart ' to deal with "Chart" object of "ChartObject" object
.ChartType = xlXYScatter ' or another XlChartType Enumeration (https://msdn.microsoft.com/en-us/library/office/ff838409.aspx)
MsgBox .ChartArea.Name
.HasLegend = False
.ChartTitle.Caption = "chart title you need"
End With
End With
Next chartObj
End With
End Sub

You can use for each to loop through charts if you arent sure with indexes. Something like this
Sub testChart()
Dim testSheet As Worksheet
Set testSheet = Sheets("Sheet1")
Dim myChart As ChartObject
Dim chartVariable As Chart
With testSheet
For Each myChart In .ChartObjects
Set chartVariable = myChart.Chart
Next myChart
End With
End Sub
warning: its only demo version, it will need further changes depends on what you need

Related

Excel macro for chart based on selection with custom name

I already found macro to create chart based on selection
Sub Charter()
Dim my_range As Range
Set my_range = Selection
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnStacked
ActiveChart.SetSourceData Source:=my_range
Cells(1, 1).Select
End Sub
but cant figure out how to give it custom name (not generic Chart <number>) so that I can build another macros around it. I found couple of ways to create chart with name but I cant figure out how to connect those two macros.
Any ideas what to do?
Thank you
You can't set the Name property of the ActiveChart. You have to go for its parent object:
ActiveChart.Parent.Name = "Bananas"
I would recommend not to use ActiveSheet, Selection, Select and ActiveChart, instead use fully qualified objects, like in the code below:
Option Explicit
Sub Charter()
Dim MyCht As Object
Dim my_range As Range
Dim ws As Worksheet
' avoid using ActiveSheet, instead use fully qualifed objects
Set ws = Worksheets("Sheet1") ' <-- change "Sheet1" to your sheet's name
Set my_range = Selection
' set the Chart
Set MyCht = ws.Shapes.AddChart2
With MyCht ' modify the chart's properties
.Chart.ChartType = xlColumnStacked
.Chart.SetSourceData Source:=my_range
.Name = "My Chart"
End With
End Sub

Using charts with VBA

I'm trying to generate two charts using VBA. The problem is most examples use ActiveChart but I want multiple charts on multiple sheets. If I inserted a blank chart how do I rename that chart to reference it. I don't want a new chart to be generated each time I run the macro and I want it to be in the sheet. I'm struggling with the code but am assuming it will be something like the code below. I've attached the desired graph (I made this through excel, but I need to do it through VBA).
macro1()
lastrow2 = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row
dim chart1 as chart
dim chart2 as chart ' ect
chart1.title = "test"
chart1.xaxis = sheet1.cell(lastrow2,1)
chart1.yaxis = "manhours"
end sub
using a the record function, i got the code commented below. I tried to change it but i'm still having issues
Sub Macro7()
Dim Chart2 As ChartObject
Dim chartb As Chart
Chart2 = Sheet1.chartb.SeriesCollection(2)
chartb.Select
Formula = "=SERIES(Master!R3C3,Master!R4C1:R18C1,Master!R4C3:R19C3,2)"
' ActiveChart.SeriesCollection(2).Select
' Selection.Formula =_
'"=SERIES(Master!R3C3,Master!R4C1:R18C1,Master!R4C3:R19C3,2)"
End Sub
I really just need this formula converted to i can reference my lastrow function and individual sheets
ActiveChart.SeriesCollection(2).Select
Selection.Formula =_
"SERIES(sheet1.cells(3,3),sheet1.cells(4,1):sheet1.cells(18,1)_
,sheet1.cells(4,3):sheet1.cells(4,19),2"
' Selection.Formula"_
' =SERIES(Master!R3C3,Master!R4C1:R18C1,Master!R4C3:R19C3,2)"
this was what i was trying to do. It declares the sheet name and references an existing chart named chart 1.
Dim cht As ChartObject
Dim rng As Range
Set cht = Sheets("Master").ChartObjects("Chart 1")
Set rng = Sheets("Master").Range("A4", Range("D4").End(xlDown).Offset(-1))
cht.Chart.SetSourceData Source:=rng
cht.Chart.HasTitle = True
cht.Chart.ChartTitle.Text = "Bird Report - By Cost Code/Activity" ' title
cht.Chart.SeriesCollection(1).Name = "=Master!$B$3"
cht.Chart.SeriesCollection(2).Name = "=Master!$C$3"
cht.Chart.SeriesCollection(3).Name = "=Master!$D$3"

excel vba chart on a different sheet using that sheet's data

I have a program that creates a new sheet, adds data to that sheet, and the last part it should do is chart that output. When I try the code below, I get "object or variable or with block variable not set"
please let me know where I am going wrong. thank you.
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range("J2", Sheets(ws.Name).Range("L2").End(xlDown).Address)
ActiveChart.ChartType = xlLine
With ActiveChart.Parent
.Height = 400
.Width = 800
End With
Next
You are using a comma to create your range with strings. That only works with range objects. Try:
ActiveChart.SetSourceData Source:=ws.Range("J2:" & ws.Range("L2").End((xlDown).Address)
With ws.ChartObjects.Add(Left:=100, Width:=375, Top:=75, Height:=225)
.Chart.SetSourceData Source:=ws.Range("J2", Sheets(ws.Name).Range("L2").End(xlDown).Address)
.Chart.ChartType = xlLine
End With
A lot of object accessors in vba return variant.
If you have this issues, for example chart.parent //returns variant btw
the first thing to try is to assign it to a typed variable
At run time if variant is dealt with as if it were a different type you will almost certainly get a runtime error.
dim ws As Worksheet
set ws = ActiveChart.Parent
With ws
'ws operations here
.Name = "My worksheet!"
.Cells(1,1).Value = "cell A1"
End With
Also its worth noting that Workbook.Worksheets collection also contains the chart objects http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.worksheets.aspx
so when you are adding a chart a worksheet you are essentially adding to the collection you are iterating over which is not advised.
Change to this:
ActiveChart.SetSourceData Source:=Range(Sheets(ws.Name).Range("J2"), Sheets(ws.Name).Range("L2").End(xlDown))

Unable to get named range in Excel

I have a worksheet where there is a chart on the first sheet, showing some data from a named range.
The named range looks like this:
=OFFSET(chart_data!$B$2,0,0,COUNTA(chart_data!$B:$B)-1)
where chart_data is a different sheet.
I also have a VBA script that is supposed to set colors of the chart same as background colors of corresponding cells. The script follows:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cht As ChartObject
Dim i As Integer
Dim vntValues As Variant
Dim s As String
Dim myseries As Series
Dim nRange As Range
For Each cht In ActiveSheet.ChartObjects
For Each myseries In cht.Chart.SeriesCollection
If myseries.ChartType <> xlPie Then GoTo SkipNotPie
s = Split(myseries.Formula, ",")(2)
vntValues = myseries.Values
For i = 1 To UBound(vntValues)
If Range(s).Cells(i).Interior.Color <> 16777215 Then
myseries.Points(i).Interior.Color = Range(s).Cells(i).Interior.Color
End If
Next i
SkipNotPie:
Next myseries
Next cht
End Sub
My problem is that when I try to evaluate Range(s), where s = "report!values_list", I get
Run-time error '1004':
Method 'Range' of object '_Worksheet' failed
How can I solve this?
Try to do it on different Office. It works for me, some of Offices blocked the dynamic range. Try to make it on different PC with different type of MS Office and make them some simply task with dynamic range. If it will work, you just copy your code there and it will work even in your sheet.
You can get the range corresponding to a name like this:
ThisWorkbook.Names ("somename").RefersToRange

VBA looping through all series within all charts

I'm having an issue with the looping through of several charts in my VBA code. I'm 99.7% sure that this is a really easy and quick fix but my brain isn't working today.
I want the code to loop through every chart on the ActiveSheet, and for every data series that the chart contains I want it to add the last value of the series. In my example I have 9 charts, each with 3 series in them (bound to change, some have 2 but I digress).
I have the following code
Sub AddLastValue()
Dim myChartObject As ChartObject
Dim myChart As Chart
Dim mySrs As Series
Dim myPts As Points
With ActiveSheet
For Each myChartObject In .ChartObjects
For Each myChart In .Chart
For Each mySrs In .SeriesCollection
Set myPts = .Points
myPts(myPts.Count).ApplyDataLabels Type:=xlShowValue
Next
Next
Next
End With
End Sub
If I remove the looping code and just do a
Set myPts = ActiveSheet.ChartObjects(1).Chart. _
SeriesCollection(1).Points
myPts(myPts.Count).ApplyDataLabels type:=xlShowValue
Then it works for that specific chart and series, so I'm positive it is the looping that I'm messing up.
Could someone tell me where I mess up the looping code?
Try following code:
Sub AddLastValue()
Dim myChartObject As ChartObject
Dim mySrs As Series
Dim myPts As Points
With ActiveSheet
For Each myChartObject In .ChartObjects
For Each mySrs In myChartObject.Chart.SeriesCollection
Set myPts = mySrs.Points
myPts(myPts.Count).ApplyDataLabels Type:=xlShowValue
Next
Next
End With
End Sub
Not work for empty values.
This code find last not empty value and then adds label.
For Each mySrs In myChartObject.Chart.SeriesCollection
Set myPts = mySrs.Points
Dim i As Integer
i = myPts.Count
Do Until i < 2 Or mySrs.Values(i) <> ""
i = i - 1
Loop
myPts(i).ApplyDataLabels Type:=xlShowValue
Next