Excel macro for chart based on selection with custom name - vba

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

Related

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"

VBA code to select columns based on user defined variables in cells

I am trying to write a code for my macro in excel with VBA but I keep getting stuck on the user defined variable part. I currently have a spreadsheet with four sets of measured data that correspond to a single date.
What I am trying to achieve is:
-Have one cell for a start date, and another cell for an end date that is specified by the user; I want to macro to read these two cells and use these two dates, read the data between them, and create a line graph corresponding to these dates with the 4 data series I have.
The end goal is to be able to create a chart between whichever two dates the user wishes to.
I have figured out the macro to plot the line graph if I specify the entire column (i.e. I have put B3:F170 as the data range) however I am not sure how integrate a user defined range in the code.
Any help would be greatly appreciated. Many thanks in advance.
Edit: Here's what I have so far, sorry if its quite messy I am just starting out!
Dim chtChart As Chart
Set chtChart = Charts.Add
With chtChart
.Name = "Chart Name"
.ChartType = xlLine
.SetSourceData Source:=Sheets("Sheet1").Range("B3:F170"),_
PlotBy:=xlColumns
End With
Dim FromDateCell As String
Dim ToDateCell As String
Dim DateRange As Range
FromDateCell = Range("I13").Value
ToDateCell = Range("I14").Value
DateRange = Range(FromDateCell, ToDateCell)
Range(DateRange).Select
you could first set the wanted data range and then assign it as your new chart Source, like follows:
Option Explicit
Sub main()
Dim chtChart As Chart
Dim FromDateCell As Range, ToDateCell As Range, DataRange As Range
With Sheets("Sheet1") '<--| reference your relavant sheet
Set FromDateCell = .Range("B3:B170").Find(.Range("I13").Value, LookIn:=xlValues, lookat:=xlWhole) '<--| get "initial date" cell in range B3:B170
Set ToDateCell = .Range("B3:B170").Find(.Range("I14").Value, LookIn:=xlValues, lookat:=xlWhole) '<--| get "final date" cell in range B3:B170
Set DataRange = Range(FromDateCell, ToDateCell).Resize(, 5) '<--| set the "data" range as the one ranging form "initial date" to "final date" cells extended to enclose four columns to the right
End With
Set chtChart = Charts.Add
With chtChart
.Name = "Chart Name"
.ChartType = xlLine
.SetSourceData Source:=DataRange, PlotBy:=xlColumns
End With
End Sub
the same code could be rewritten (i.e. refactored) to use a specific function to get the wanted range and have your main code more readable and the whole code more maintainable
like follows:
Sub main()
Dim chtChart As Chart
Set chtChart = Charts.Add
With chtChart
.Name = "Chart Name"
.ChartType = xlLine
.SetSourceData Source:=GetDataRange, PlotBy:=xlColumns '<--| here you use GetDataRange() function to return the wanted range
End With
End Sub
Function GetDataRange() As Range
Dim FromDateCell As Range, ToDateCell As Range
With Sheets("Sheet 1")
Set FromDateCell = .Range("B3:B170").Find(.Range("I13").Value, LookIn:=xlValues, lookat:=xlWhole)
Set ToDateCell = .Range("B3:B170").Find(.Range("I14").Value, LookIn:=xlValues, lookat:=xlWhole)
Set GetDataRange = .Range(FromDateCell, ToDateCell).Resize(, 5)
End With
End Function
I think you can achieve this quite simply by using named ranges. Define a named range with the formula
=OFFSET(A8:E200,0,<column>)
Enter that as the data series as input range for the graph as
=<sheet1>! <name>
Replace all values between < and > to whatever is applicable to you. See full reference at https://support.microsoft.com/en-us/kb/183446
You can also use the offset formula in combination with index/match to find the starting/end point in order to get a subset of your data.

VBA Excel 2010 - Assign unknown chart to varible

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

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))

copying activex controls along with the macros

Is it possible to copy an ActiveX control to a different worksheet along with the macro associated with it?
Thanks
code to copy a forms button
activesheet.buttons("Button 1").copy
sheets("Sheet1").range("A1").pastespecial
or you can create a new one using Buttons.Add
Dim ws As Worksheet
Dim rTarget As Range
Set ws = Sheets("Sheet1")
Set rTarget = ws.Range("A1")
With ws.Buttons.Add(Left:=rTarget.Left, Top:=rTarget.Top, Width:=rTarget.Width, Height:=rTarget.Height)
.Caption = "Some text"
.OnAction = "Some_macro"
End With
finally, simply copying the range should work unless application.copyobjectswithcells is set to False
You can have a commandbutton or combobox from another sheet access the same macro.