Powerpoint VBA - Set DataRange for DataLabels - vba

I have no idea how to set DataRange for DataLabels using VBA.
Powerpoint does not have recording capabilities as well.
Can anybody tell me to do this using VBA please?

The code to accomplish this is as follows:
Dim myChart As Chart
Dim mySerCol As SeriesCollection
Dim strRange As String
strRange = "=Sheet1!$F$2:$F$5" 'To hold the range for the new labels
Set myChart = ....[put in code to get the appropriate chart]
Set mySerCol = myChart.SeriesCollection(i)
mySerCol.ApplyDataLabels 'Turn on the datalabels for this series
'The next line sets the range to get the values from
mySerCol.Format.TextFrame2.TextRange.InsertChartField msoChartFieldRange _
, strRange, 0
mySerCol.ShowRange = True 'Show the values from the range
mySerCol.ShowValue = False 'Do not show the actual values of the points
Note that this will only do this for one of the series. To do the other ones, loop through i in the myChart.SeriesCollections(i) line.

****EDIT**** See other answer. I am leaving this here because it provides some information about several objects that could be used, but doesn't actually solve the problem.
This is not a complete answer to the issue, but this is too long for a comment.
I've searched through the documentation for the Datalabels and was unable to figure out how to do this (I assume that you want to be able to define the range that the labels come from using VBA). I was able to "check" the checkbox, but couldn't figure out where the range that is attached to it is. The appropriate code to check.
To check the checkbox, use this code:
myChart.SeriesCollection(i).ApplyDataLabels
where i is the series in question and myChart is a Chart object referencing your chart. There are a bunch of parameters to this method that will allow you to show different items (percentages, values, etc.), but none of the parameters is a range.
This defaults to the values of the series if you do not enter any of the optional parameters
It is then possible to turn this on and off using:
myChart.SeriesCollection(i).DataLabels.ShowRange = True/False
It is possible to change the caption of the Datalabels using:
myChart.SeriesCollection(i).DataLabels(j).Caption = "MY CAPTION"
This will change the caption one at a time, and it will replace the value that the "ApplyDataLabels" method puts in there. It would be possible to loop through the range to set the values, but this is likely not what you are looking for.
There's also this:
myChart.SeriesCollection(i).HasDataLabels = True
but this just seems to turn them on and off and resets the captions that you may have put in there.
MSDN link uses both the hasdatalabels property and the applydatalabels method, but it is not clear why they are using both: https://msdn.microsoft.com/EN-US/library/office/ff745965.aspx
Hopefully this can at least give you something to start with.

Related

Word macro to set image layout and size

I'm trying to record a macro that will set the size of a pasted image to 6.5 x 4 cms and the image layout 'in front of text'. I usually set this by right clicking on the image and setting the picture properties but this isn't available when recording the macro. Using Shift-F10 does bring up the menu, but the option to set the image layout properties is greyed out.
Please help!
Thanks
Yes, that's interesting about the macro recorder...
If you need to do something like this in the future it will help you to know that an object with any kind of "text wrap" formatting (that "floats") is a Shape. An object that behaves like a character is an InlineShape. And you can convert between the two using ConvertToInlineShape / ConvertToShape. For future things of this nature that should give you a starting point :-)
The following code sample uses ConvertToShape so that text wrap formatting can be applied. (The conversion is an extra step involved that you don't have to do in the UI - Word does it for you.)
Before this happens the code changes the size, but it could also be the other way around, changing the size on the Shape object.
What else is happening in the code: When a picture is pasted inline it's not selected. So this code figures out how many pictures (InlineShapes) are already in the document up to the selection. After the paste the code then picks up the existing number of pictures up to that point, plus one, to get the picture that was just pasted.
The code uses CentimetersToPoints to convert the number of centimeters wanted to the Points measurement, since that's what Word uses to size graphical objects (and lots of other things).
How did I know to use wdWrapFront: When shp.WrapFormat.Type = is typed the VBA Editor will automatically show a list of valid entries for text wrap formatting. Similarly, when shp. is typed a list of valid properties for a Shape will appear, and so on. (This is called IntelliSense and is a wonderful help!)
Sub PasteAndSelectPicture()
Dim ils As Word.InlineShape
Dim shp As Word.Shape
Dim lNrIls As Long
Dim rngDoc As Word.Range
Dim rngSel As Word.Range
Set rngDoc = ActiveDocument.content
Set rngSel = Selection.Range
rngDoc.End = rngSel.End + 1
lNrIls = rngDoc.InlineShapes.Count
rngSel.Paste
' Debug.Print rngDoc.InlineShapes.Count, lNrIls
Set ils = rngDoc.InlineShapes(lNrIls + 1)
ils.width = CentimetersToPoints(6.5)
ils.height = CentimetersToPoints(4)
Set shp = ils.ConvertToShape
shp.WrapFormat.Type = wdWrapFront
End SUb

Filling a variant array with charts in Excel VBA

I am working on a file that creates up to 120 charts based on data, variables, and format selections from the user. To do this I create a variant array to hold the charts which allows me to easily reference them for adding data, formatting, etc. This method has worked well for me so far.
Now I would like to let users make small tweaks to formatting (adjust the min and max on the axis, add or remove legend entries, etc.). To do this I would like to continue referencing the charts from an array, but I can't seem to add the existing charts to the variant array.
When I initially create the charts I use this line to add the chart to the array when it is created. I fill in appropriate parameters to place and size the chart and this seems to work fine.
Set charts(graphIndex) = activeSheet.ChartObjects.Add(...)
After creating all the charts, I think the non Global variables used are cleared from the cache (at least that is my current understanding). This means that in order to make these tweaks I need to reinitialize and redefine the variant array that I use to reference the charts. This is what I am struggling with. This is my current attempt to add the existing chart to the variant array.
charts(graphIndex) = Worksheets(activeSheetName).ChartObjects("chart name").Chart
When I run the code I am getting a "Run-time error '438': Object doesn't support property or method."
Hopefully I provided enough context, but any help on this would be greatly appreciated. This feels like it should be fairly easy, but I couldn't find any information online.
I am just guessing that in your code if you had the Set word it would have worked (However, I am not seeing the whole code, thus not sure).
This works, if you make sure to have 3 charts named "Diagramm 1", "Diagramm 2" and "Diagramm 3" on the first worksheet:
Option Explicit
Sub TestMe()
Dim cht2 As Chart
Dim varArray As Variant
With Worksheets(1)
Set cht2 = .ChartObjects("Diagramm 2").Chart
varArray = Array(.ChartObjects("Diagramm 1").Chart, cht2)
ReDim Preserve varArray(2)
Set varArray(2) = .ChartObjects("Diagramm 3").Chart
Dim cnt As Long
For cnt = LBound(varArray) To UBound(varArray)
Debug.Print varArray(cnt).Name
Next cnt
End With
End Sub
The Reedim Preserve increases the array units with one additional, while it keeps what it already has. Thus, at the end this is what we have in the locals:

Jump to Cell Based on Value in Another Cell (Macro LibreOffice VBA)

I want to be able to jump to a cell based on the user entering a date (in B14).
In column F, I have a list of dates (starting at row 8).
So far, I have =MATCH(B14,F8:F373)+7 (in B15) which calculates which row the right date is in, and returns a number.
I need to write a macro in LibreOffice VBA that will select the cell in that row, in column G. So far, I have:
sub jump
dim document as object
dim dispatcher as object
document = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
Doc = ThisComponent
Sheets=Doc.Sheets
sheet=Sheets.getByName("ThisYear")
dim args1(0) as new com.sun.star.beans.PropertyValue
thisrow =sheet.getCellByPosition(15,2).getValue()
args1(0).Name = "ToPoint"
args1(0).Value = (G,thisrow)
dispatcher.executeDispatch(document, ".uno:GoToCell", "", 0, args1())
end sub
But it doesn't accept the value being in the form (column, row). I have seen before I need something like args1(0).Value = "G15" but how can I include the variable? (I have tried using 7 instead of G but this doesn't help.)
I have mentioned the sheet name, sheet=Sheets.getByName("ThisYear"), but it is all within the one sheet so ideally I wouldn't want to specify this so I could use the macro in different sheets.
I am new to VBA so please reply with the whole sub.
Thanks!
I understand that you are having trouble figuring out how to change the cell selection in LibreOffice Calc. Here is a code snippet that shows you how. In short, you identify a targeted range (oRange) (which below is a single cell at location 3,3), and then pass that object to the .select() method.
Sub ChangeSelection
oSheets = ThisComponent.Sheets
oSheet = oSheets.getByIndex(0)
oRange = oSheet.getCellByPosition(3,3)
ThisComponent.CurrentController.select(oRange)
End Sub
LibreOffice uses uses the UNO API documented here. If you want to browse the properties and methods for an object, use MsgBox oObject.DBG_properties or .DBG_methods, you usually will be able to find the right thing eventually. The code snippet in your question returns an error that I could not immediately figure out.

Recorded macro for data labels does not work

So, I'm a novice at using VBA but not so new that I know not to use .select and the likes wherever possible but I will still record macros to find out how to call certain objects. I am working on a large piece of code to do various things before manipulating a chart at the end, it wasn't working so breaking it down into a new spreadsheet I found that some of my lines for manipulating chart labels were giving me an error. I recorded a macro to make sure I hadn't mis-typed anything, but could not fix it, then tried to run the recorded macro, but couldn't get it to work.
Heres the aim of my code:
1. Apply data labels to one point in a series.
2. Delete the label I just applied
(in the final code there will be "if" functions ect)
Here is the macro code, straight from the recorder:
ActiveSheet.ChartObjects("Chart 1").Activate
ActiveChart.SeriesCollection(2).Select
ActiveSheet.ChartObjects("Chart 1").Activate
ActiveChart.SeriesCollection(2).Points(1).Select
ActiveChart.SeriesCollection(2).Points(1).ApplyDataLabels
ActiveSheet.ChartObjects("Chart 1").Activate
ActiveChart.SeriesCollection(2).Points(1).DataLabel.Select
Selection.ShowValue = 0
Selection.ShowCategoryName = -1
' this line ^ gives error 438, object does not support this property or method
ActiveSheet.ChartObjects("Chart 1").Activate
ActiveChart.SeriesCollection(2).Points(1).DataLabel.Select
Selection.Delete
What's also very curious is that sometimes rather than Selection.ShowValue = 0 it will use Selection.ShowValue = False
Anyone know why the recorded code for this is so jumpy? Also if anyone could suggest simpler code for manipulating data labels that would be very useful.
I am using excel 07 on windows 7.
Charts in VBA have always been a pain in the rear for me. That being said, here's some code that tosses a few of the more common objects into variables (so you can break the code on a line and see what's going on in the "locals" window). This will iterate through all of the points on your chart and add a datalabel containing the "Value".
Sub test()
Dim myChart As ChartObject 'A "ChartObject" contains a Chart, in which the "SeriesCollection" resides
Dim chartSeries As Series 'Multiple "Series" can be found in a "SeriesCollection"
Dim scPoint As Point
Set myChart = ActiveSheet.ChartObjects("Chart 1")
Set chartSeries = myChart.Chart.SeriesCollection(1) 'Get the first "Series" in the "SeriesCollection" for this chart
'loop through the points in this Series. As it loops the point will be available in the "scPoint" variable.
For Each scPoint In chartSeries.Points
With scPoint.DataLabel 'Finally the "DataLabel" is part of the "Point"
.ShowValue = True 'Just show the value. There are other options here, just create a new line and start typing with a period to see what other options are available for a "DataLabel"
End With
Next scPoint
'Instead of iterating, if you just want to address a single point's datalabel then:
chartSeries.Points(2).DataLabel.ShowValue
End Sub

VBA: Defining CurrentChart as the string in a cell

I'm looking to find a way to set the current chart as whatever I have in a a cell in an array. For example, my array will have Chart_1_4301 as the first listing, and I then want to set the chart, which is also named Chart_1_4301, as the CurrentChart.
Rather than saying
If Array_Name(i) = "Chart_1_4301" Then
'Some sort of code
End If
If Array_Name(i) = "Chart_1_4404" Then
'Some sort of code
End If
If Array_Name(i) = "Chart_1_4552" Then....
ect. Is there a way to set the CurrentChart as the name of the chart, whose name is stored in a cell?
I just want to say something like: Set CurrentChart = Array_Name(i)
I know something like this is possible in MATlab (which is the only other programming I've done) but I don't know the syntax in VBA. Any help is greatly appreciated!
For better assistance, it is helpful to post more of your code. Varocarbas gave some suggestions, above.
I will give you another suggestion based on a different interpretation of your incomplete question. Since I do not know what Type is the CurrentChart (i.e., is it a ChartObject or a Chart?)
Assuming you're doing some sort of loop/iteration over the array of names, and you want to operate on each chart in sequence:
For i = lBound(Array_Name) to UBound(Array_Name)
Set CurrentChart = ActiveSheet.ChartObjects(Array_Name(i))
Next