Some background first.
Excel allows duplicate names for shapes. That is, you can have both a ChartObject and an oval shape in the same worksheet with exactly the same name. You can also have two charts named both "Chart 2". If you try to reference a shape with a duplicate name, e.g.
ActiveSheet.Shapes("Dupe").Select,
excel seems to resort to returning the object with the lowest ID (and the duplicate name).
There is no way (that I know of) of linking an ActiveChart with its corresponding containing shape.
I want to create a function like
function GetAChartsShape(c as chart) as Shape,
but I don't know how. The immediate use for this would be to format the selected chart (since there is no way of globally changing a chart's font). Of course, this could also have other uses.
The name of the shape containing an embedded chart (the shape is also the chartobject) is:
activechart.parent.name
or if c is declared a chart:
c.parent.name
But of course you know you don't need to select an object to work on it, so just do what you need to do on
c.parent
which avoids the problem of duplicate names.
Related
I have a VBA code that opens a workbook. It then does the following:
ThisWorkbook.Sheets("Sheet1").Shapes.SelectAll
Selection.Delete
I thought after the SelectAll, the Selection should be the shapes just being selected, which are what I want to delete. No. It's not. It's the active cell in the just-opened workbook and it's that active cell that's deleted. Usually, Selection after Select refers to the objects just being selected. Apparently, in the case of SelectAll, that's not true. How to set the focus to the just-selected shapes?
I changed my approach by doing SelectAll then assigned the selected shapes to a shaperange object following the method in Microsoft Docs. The method is in the following:
Set myDocument = Worksheets(1)
myDocument.Shapes.SelectAll
Set sr = Selection.ShapeRange
My code is:
ThisWorkbook.Sheets("Sheet1").Shapes.SelectAll
Set sr = Selection.ShapeRange
Unfortunately, that document doesn't say what the sr is declared to. I have declared it as a shape, shapes, ShapeRange, Object, Variant. In every case, Excel complained "Object doesn't support this property or method." I wonder what it's set to in the MS document.
I know I can delete all shapes using a For loop but I'm trying to avoid doing a loop.
ThisWorkbook.Sheets("Sheet1").Shapes.SelectAll
Selection.Delete
is fundamentally wrong because it attempts to convert a Shapes Collection into a Selection object.
The Selection object exists entirely and almost exclusively for the use and benefit of the user: the user may select something to show to VBA or VBA may select something to show to the user. In your example the user is excluded from the process. Therefore involvement of the Selection object is a waste of time and resources. You wouldn't have to ask your question if you weren't trying to make something work that isn't designed to work in that way.
The correct approach is to identify the object and do with it whatever you want. The object is either the collection of all shapes on the worksheet (ThisWorkbook.Sheets("Sheet1").Shapes) or any member of it, such as ThisWorkbook.Sheets("Sheet1").Shapes(1). You also have ThisWorkbook.Sheets("Sheet1").Shapes.Count at your disposal to loop through them all or For Each Shp in ThisWorkbook.Sheets("Sheet1").Shapes.
The ShapeRange object contains another collection. It's name promises a smaller collection than all shapes on the sheet. Don't let the choice of collections confuse you. The job is to identify one or several shapes and delete them. The fact of the matter is that you do have to deal with a member of a collection and not the Selection object.
how to retrieve the reference to the chart and to the worksheet where the chart of the gridline object is, starting from the object itself?
For example, if I have a Range object, the object.Parent is the reference to the Worksheet.
How to do it if the starting object is the gridline object of a chart embedded into a worksheet?
Thanks in advance to everyone can help to put me in the right direction
I start using the answer of the post stackoverflow.com/questions/24045305. Then I added a For.. Next cycle through the worksheets collection (I don't have only one sheet and it is not always the same Chart of interest).
Furthermore, because of the AxisTitle caption is currently meaningful for me and its value is based on a cell formula result (it can't be prefixed and formatted to be white and the rest leaved to be automatic), I solved the problem adding a textbox whose value is now the cell formula result and the AxisTitle caption contains now only the unique identifier formatted to be white.
I have the same snippet of code opening three different macros...
Set c = ActiveSheet.Shapes(Application.Caller)
In two of them, that line captures the shape I need just fine. In the third, it throws...
Run-time error '-2147024809 (80070057)':
The item with the specificed name wasn't found.
Yet when I debug and highlight Application.Caller in this problem macro, I can see it knows what shape it's looking at (in this case, msoShapeSnip2SameRectangle). The ones that work are msoShapeDownArrow and msoShapeMathMultiply, if that makes any difference.
Any ideas on why it's not working in this third macro? I've tried defining it both as a Shape and Object first.
Seems like there's a length limit to the value passed to Application.Caller
If I insert that shape type to a sheet I get a shape called "Snip Same Side Corner Rectangle 1" (length=33), but the value passed to Application.Caller is "Snip Same Side Corner Rectangl" (length=30)
Note it's not a problem with the specific shape type, just the length of the default name. If you rename the shape to something shorter it should be fine.
EDIT: previously - How to get the Shape Clicked without Application.Caller
I have an Excel Sheet with some macros. Also, I have some navigation shapes and images on my sheet. I want users of this sheet, cannot change this shapes and images positions, can't select them and can't move them.
Is there any way to Protect some specific objects?
Regards.
I believe this is an age old question ever since Shapes were added to MS Excel and the answer to which I myself was looking for many years already.
I just found out 3 days ago, on my own, how to lock MS Excel Freeform shapes like Choropleth Map shapes from being moved around, reformatted or worst, deleted, all WITHOUT needing to lock the WorkSheet, or eventually the WorkBook.
And I think I must share my discovery with the world because everyone wants to lock their Shapes!
Steps: (I work with Excel VBA and with msoFreeform shapes mostly but I think any shape should be working and manually added shapes through Excel UI should work too and in other Office Apps as well)
1.(yourWorkSheet or )ActiveSheet.Shapes.AddChart (through VBA but MAYBE you can add chart through Excel UI and then delete the only chart)
(no need for any other parameter because we just need the chart container, "ChartObject")
2.If you don't have some already, create a shape either through Excel UI or through VBA with AddShape method or BuildFreeform on the Chart directly or on to the worksheet.
3.Copy/Paste the created shape (if created through Excel UI or through VBA on the worksheet) on to the BLANK Chart Container. (NOT drag and drop)
4.Format the ChartContainer Rectangle window as required (try "No Fill & No Outline") through VBA or Excel UI
5.There are 3 options regarding protection of a Chart
(Embedded chart here because I don't work with Chart Sheets, may be this might work with them)
source:[https://peltiertech.com/Excel/ChartsHowTo/ChartProtection.html]
But here, only the relevant 2 will be shown:
5(a)ActiveChart.ProtectFormatting = True
That protection will block any formatting changes on the Shape and the Chart via "Chart Tools Menu" or "Drawing Tools - Format Menu" or moving or resizing with mouse or deleting BUT will show the ChartContainer window upon Selection via Mouse but non-selectable via VBA
eg. yourworksheet.ChartObjects("YourChartName").Chart.ProtectFormatting=True
5(b)ActiveChart.ProtectSelection = True
That will stop the shape or the chart from being selected altogether so this is the end of story
eg. yourworksheet.ChartObjects("YourChartName").Chart.ProtectSelection=True
The best thing about this method is that the shape can still be accessible through VBA like
eg.yourworksheet.ChartObjects("YourChartName").Chart.Shapes("YourShapeName or Index").whatever
except Shape.Select which should be obvious and there is NO need to lock the Worksheet or Workbook at all.
NB:1)The interesting finding here is that the 2 protections do not replace each other (if applied one after another) but more like stacked with each other meaning if both (if you really want) were set True first and then after setting either one False, the other restriction still remains.
2)Even if selection is protected as above, the chart can still be accessible through the Selection Pane, therefore:
Application.CommandBars("Selection and Visibility").Enabled = False
and also blocking the Worksheet Export are advisable but I think these are overkill nonetheless included for completeness' sake.
Discovered and tested on MS Excel 2010 so YMMV.
Nay Lynn's answer caused my Excel to crash. Specifically with the .ProtectSelection property being enabled (using Microsoft365 Excel). . . Excel VBA's Intellisense shows the property, so it is legitimate, but everything would be fine until the chart was selected. Playing around with this idea though, I did find a great work around.
1. Place a Chart on your sheet. Make it span across the area you want to protect
(we will expand the size of this chart later).
a. Leave Fill of Chart at Default until a later step (this helps ensure the
next steps are successful).
b. Delete all the elements present for the chart (Series label, Title, Etc.)
c. Shrink the "Plot Area" box leftover to as negligible as possible.
d. CRITICAL: Right Click the chart and choose "Select Data" - use the
option to remove all the data in the boxes of this dialog, otherwise when
you select the Rectangle added below, it will show the data references as
selections in the Worksheet behind it.
2. Insert a Rectangle into the Chart. It will have the default colors.
3. Tap `Esc` to clear the selection. If you select the shape and try to move it
around, it will take precedence over the Chart itself (this is how we'll trick
Excel later).
a. Confirm this does not allow the shape to be pulled beyond the border of the
Chart.
4. Set Fill of Chart to be "No Fill"
5. Expand the Rectangle's size to match the size of the chart.
6. Set Fill of Rectangle to be a color with 100% Transparency (NOT the same as "No
Fill" - this is critical)
a. You should be able to see all of your shapes, etc, but not touch them if you
click where the rectangle was, and trying to click and drag will also fail since the
Rectangle takes selection precedence and is also bound by the chart.
7. Set the fill of the Rectangle back to a color with 0 transparency (we need to
find the edge of the shape)
8. Select the Rectangle's border and it should then select the Chart instead (you
should see the chart Format option appear).
9. Expand the Chart's border to the ends of the Excel Sheet (ensure the top left
corner sits in the top left corner of the sheet by dragging it). You can also set
the height/width to an absurd number that users will get fed up with trying to find
if you do not wish to expand it across the entire boundaries (or if there's a hard
limitation - I did not try to expand across the entire sheet, but went to "BO400"
with no issue.
a. Expand the Rectangle to fit the Chart once again if it did not expand
automatically (in my case it did, but I cannot guarantee this behavior)
b. If you have any Buttons that DO need to be clicked, place this chart
at the bottom, place all the buttons/shapes etc. that need interaction to
the top, then bring the chart up a level until all the items needing
protection are hidden.
c. Change the Transparency back to 100%
10. After you have the Chart expanded properly, you will need to use a bit of VBA
to ensure the Chart's Formatting is protected as Nay Lynn mentions. Get the
Chart's name by selecting the border, and institute some VBA Code that gets
toggled based on your needs (you might want to include an unprotect sub
as well just in case).
Example:
Sub Protect_Sheet_With_Chart ()
dim sht as Worksheet
dim chrt as Chart
Set sht = ActiveSheet
'You can use a sheet by name for the above as well - make your code robust.
Set chrt = sht.ChartObjects("ChartNameFoundFromStep10").Chart
chrt.ProtectFormatting = True
End Sub
Sub UnProtect_Sheet_With_Chart ()
dim sht as Worksheet
dim chrt as Chart
Set sht = ActiveSheet
'You can use a sheet by name for the above as well - make your code robust.
Set chrt = sht.ChartObjects("ChartNameFoundFromStep10").Chart
chrt.ProtectFormatting = False
End Sub
11. After you protect the Chart, selecting it and deleting will not
actually delete it, NOR the rectangle, so it can't be removed!
12. Protect your code somehow and you'll be set!
So, I've created a dynamic range for a chart, that's all well and easy.
However, in this chart there are two lines, but I only want one of the lines to show up under certain conditions, else it displays nothing! So I've tried creating my dynamic range as follows
=IF('WorksheetName'!$M$10 ='WorksheetName'!$F$31,'WorkSheetName'!dynamic_range, #N/A)
The problem is that when I do this the chart freaks out. It gives me this error:
Your formula contains an invalid external reference to a worksheet.
Verify that the path, workbook, and range name or cell reference are
correct, and try again.
If I click "ok" half the time it shows up correctly (that is, the second line disappears and the chart adjusts accordingly) and the other half the time it glitches.
Basically, how do I create a dynamic range for graphing that the chart will understand when I want it to do NOTHING and when I want it to display the range?
You need a second source range, that's cells are just empty. Applying your approach to switch between the filled range (intended to be visible) vs. the empty range (will be invisible), shall solve the issue. Note: The chart parameter "Show empty cells as:" should be set to "Gaps". (Refer to the Hidden and Empty Cells options in the chart's Select Data dialog. This is applicable to X/Y charts mainly.)