VBA to get selected shape name in Combobox - excel

I am new to VBA. i have few shapes in a worksheet.
I want to get the name of shape to appear in combobox and character name in another Combobox, when any particular shape is selected. so i can rename that shape and link to particular excel column.
i have tried following.
With Selection
ActiveSheet.ComboBox1.Value = ActiveSheet.Shapes(Application.Caller).Name
End with
Not sure where to assign above code.
I tried assigning above code to a shape with .onaction as macro, it work but a marco assiged shape cannot be edited further(For design purpose).
Also It would be great if i can delete selected shape.
Thank you in advance.

You can use your code for any shape and you can change the code whenever you want, but assigning a macro, she shape will will not be selected when clicked... It becomes a kind of control.
Excepting the case when you force it to select:
Debug.Print ActiveSheet.Shapes(Application.Caller).Name
shW.ComboBox1.value.Shapes(Application.Caller).Select
You can change the code from right click context (on the chart bottom side) and choose 'Assign Macro... -> Edit'.
You can find the selected shape using the next code:
Sub testSelectedShape()
Dim shW As Worksheet, sh As Object, selSh As Object
Set shW = ActiveSheet
If TypeName(Selection) <> "Range" Then
Set selSh = Selection
Set sh = shW.Shapes(selSh.Name)
Debug.Print selSh.Name
shW.ComboBox1.value = selSh.Name
End If
End Sub
You can delete it simple using sh.Delete...

Related

Detect ComboBox Change Excel VBA

I have a sheet with a bunch of ComboBoxes(form control) and I want to detect when a user changes any one of them and write text in a cell. Using Worksheet_Change on the target cells doesn't work. I have tried a bunch of things that don't work. I'm not sure what needs to be in the private sub line or the if statement.
Private Sub DropDowns_DropButtonClick()
If ActiveSheet.DropDowns.Value > 1 Then
Cells(13, 5).Font.Bold = True
Cells(13, 5).Font.Color = vbRed
Cells(13, 5).Value = "!!! Selections have been changed. !!!"
End If
End Sub
I have tried
ComboBox_AfterUpdate()
ComboBox_Change()
DropDowns_AfterUpdate()
DropsDowns_Change()
and anything else I could find. I've also tried a few different things in the if statement with no luck.
I appreciate any help.
Chris
If I'm reading you correctly, you're comboboxes are in a userform. If I'm correct, simply open your userform in 'Visual Basic' and double click on the relavant combobox. This will open the code pane and create an empty Private Sub routine called 'Private Sub <Combobox Name> ()'.
Enter your code to place your data in the sheet (or whatever else you want) into the subroutine and Bob should be your uncle.
Apologies in advance if there's something I've missed.
RannochRob
Edit...
OK, my mistake, it's a form control.
My first comment is that it's easier to use an activex control if you can... however, with a form control, should (a) Use the cell link box in the 'Format Control' drop down ('Control' tab) to place the result in a cell... however, that result will not be the content of the box but an integer equal to the position of the selected entry on the list of entries in the combobox. You then need to (b) assign a macro to the combobox which will pick up the result and use it to get the required information from the range containing the list of entries. Like I say, much easier with an activex control...
RannochRob
Here's how you can do it by assigning a macro to the combobox (right click on the combobox>assign macro) as #BigBen mentioned in the comments section:
Option Explicit
Sub DropDown1_Change()
Dim sht As Worksheet
Dim dd As DropDown
Set sht = ThisWorkbook.Worksheets("Name of your Worksheet") 'Name of the worksheet in which the combobox is located
Set dd = sht.DropDowns("Drop Down 1") 'name of your combobox
sht.Range("G1").Value = "The selected value is: " & dd.List(dd.Value) 'dd.value returns the index of the selected value
End Sub
You can use the same code for each one of your comboboxes.
For demonstration purposes i have used the following set-up:
You can easily modify the code to best fit your needs.

Selecting a shape

I am currently working on an Excel tool that I have equipped with one button and one shape-object.
The button is a select button to "select" the shape object. The idea is to Select a shape-object a Picture and change its color after selecting it.
I was able to locate the problem to the clicked Sub of the Select button.
To check if I'm correct I have written a the Macro Select_MyClicked and afterword used the call instruction to invoke the macro from within the Clicked-function of the select button.
Sub Select_MyClicked()
Dim ElementName As String
Dim Shp As Object
Set Shp = Sheets("Tabelle1").Shapes(ElementName)
Shp.Select
End Sub
==================================================================
Private Sub CommandButton3_Click()
Call Select_MyClicked
End Sub
==================================================================
What is interesting now is:
When I use the Button the Image is selected but in the Picture format register there i nothing selectable
If I cklick on the Image itselfe or use the Select_MyClicked Macro indepentently everything in the picture format register is selectable
I also tried to write the select instruction directly into the Button-Clicked private sub. Same result nothing selectable
What I want to do is select an image and change its color. My second question is does somebody know how to open the Colorpennel (with the many colored Rectangles) using vba ?
You need to reference the Shape by its Name. I assigned the name "myshape" to the Shape before running:
Sub Select_MyClicked()
Dim ElementName As String
Dim Shp As Shape
ElementName = "myshape"
Set Shp = Sheets("Tabelle1").Shapes(ElementName)
Shp.Select
End Sub
The code runs even if Tabelle1 is not the active sheet.
I have finally find the solution. It seems like it makes a difference which button you use. In my case it had to be the control elements not the activeX elements

Deleting images but can't avoid deleting command button

I'm not a regular user of vba, so when I started doing this code I was totally blank. I already deleted all the images on the worksheet, including command buttons and a logo I didn't meant to delete.
This is my code
Private Sub CommandButton2_Click()
Dim Pic As Object
Range("D20:D3000").ClearContents
For Each Pic In ActiveSheet.Pictures
Pic.Delete
Next Pic
End Sub
As you can see I need it to delete the images on the D column, but it deletes the images of the whole sheet.
I can't find a way to exclude command buttons (I'm using 2 on that sheet) of the deleting instruccion. Would some of you please, please, please help me? I'm a mess right now.
I need it to delete the images on the D column, but it deletes the images of the whole sheet.
You are iterating all pictures on the sheet, and never verify where on the sheet the picture is before you invoke its Delete method.
Interestingly, if you have one picture and one ActiveX command button on Sheet1, then Sheet1.Pictures.Count returns, unexpectedly, 2 - that's why the loop is also deleting command buttons.
I'd suggest iterating the Shapes collection instead: a Shape object has an interface that makes it much easier to tell a picture apart from an ActiveX button, ...and to know where on the sheet it's at.
Using Shape.Type we can know if we're looking at a msoPicture, and with Shape.TopLeftCell we can get a Range object representing the top-left cell the picture is located at; if the Column of that Range is 4, then we're looking at a shape whose upper-left corner is located in column D. Thus:
Dim currentShape As Shape
For Each currentShape In ActiveSheet.Shapes
If currentShape.Type = msoPicture And currentShape.TopLeftCell.Column = 4 Then
currentShape.Delete
End If
Next
Note how declaring an explicit type that isn't Object for our loop variable, we get compile-time validation, and autocomplete/intellisense for every single one of these member calls, whereas calls made against Object are all late-bound (i.e. compiles perfectly fine with typos, even if you have Option Explicit at the top of your module) and will only blow up at run-time if anything is wrong (e.g. error 438 if you try to invoke a member that doesn't exist).
The following compares the picture's range with your range and deletes it if they intersect:
Private Sub CommandButton2_Click()
Dim objPicture As Object
Dim objPictureRange As Object
Dim objRange As Object
Set objRange = Range("D20:D3000")
objRange.ClearContents
For Each objPicture In ActiveSheet.Pictures
' Get Picture's range
Set objPictureRange = Range(objPicture.TopLeftCell.Address & ":" & objPicture.BottomRightCell.Address)
' Check if Picture is in Range
If Not Intersect(objRange, objPictureRange) Is Nothing Then
' Delete picture
objPicture.Delete
End If
Next Pic
End Sub

Select chart within userform

I am looking to write a macro which copies formatting from one graph and applies it to multiple other graphs.
What I am struggling to do is determine a way to allow the user to set the template chart and then select the multiple other charts. While this could be done with a combo box if the user knew the chart name, I am trying to do it without them knowing the chart name.
As such I was thinking of having a user dialog box where the user can select the base chart, and then select the charts to apply the formatting to. Just like refedit for a range. However I cannot figure out how to reference to a graph from within a user form.
Can this be done, and if so, how?
Here is what will get you started.
Place Two ComboBoxes and two Image Controls on the userform.
Let's say your worksheet looks like this
In the UserForm_Initialize() event populate the Chart names in both the comboboxes. For example
Dim ws As Worksheet
'~~> Prepare your form
Private Sub UserForm_Initialize()
Set ws = ThisWorkbook.Sheets("Sheet1")
Dim ChartObj As ChartObject
For Each ChartObj In ActiveSheet.ChartObjects
ComboBox1.AddItem ChartObj.Name
ComboBox2.AddItem ChartObj.Name
Next ChartObj
End Sub
So when you run the form, it will look like this
In the click event of the comboboxes, use the Stephen Bullen's PastePicture code from HERE to show the chart in the userform. For example
Private Sub ComboBox1_Click()
ws.Shapes(ComboBox1.Value).CopyPicture
Set Me.Image1.Picture = PastePicture(xlPicture)
End Sub
Private Sub ComboBox2_Click()
ws.Shapes(ComboBox2.Value).CopyPicture
Set Me.Image2.Picture = PastePicture(xlPicture)
End Sub
This is how the form will look.
From there on, Now you have the names of the charts. Simply use them to work as you please.
Hope this helps.
The following code should allow you to do stuff with the selected chart area(s), where you can either select one or many charts:
Public Sub ProcessSelectedCharts()
Dim i As Integer
Dim chart_obj As ChartObject
Dim chart_area As chartArea
If TypeOf Selection Is DrawingObjects Then
For i = 1 To Selection.Count
If TypeOf Selection(i) Is ChartObject Then
Set chart_obj = Selection(i)
Set chart_area = chart_obj.Chart.chartArea
Call ProcessChart(chart_area)
End If
Next i
ElseIf TypeOf Selection Is chartArea Then
Set chart_area = Selection
Call ProcessChart(chart_area)
End If
End Sub
Public Sub ProcessChart(obj As chartArea)
' Do something...
End Sub
You may want to refine this a little, i.e. this should work if the user selects the actual charts, but may fail if he only selects a particular element within the chart.
Ok, the next question is, when do you invoke this from your user form. So first of all, your user form should be modal of course, to allow the user the select anything. So how do you notice when the users actually selects anything?
I can think of three methods, and I'll list them from best to worst (the last 2 only described very briefly as I wouldn't recommend using them):
Use the "Worksheet_SelectionChange" event on your worksheet, and have it call a method within your userform to inform it that the selection has changed. Now you'll just need to check if, and which charts have been selected (see code above), and run your algorithm.
Run a timer in your userform and regularly check the active selection.
Hook mouse events by DLL calls and register any mouse clicks, then check for selection changes.
That should allow you to create a ref-edit like feature for selecting charts on your worksheet from a userform.

Excel 2010 command button disappears

I'm developing an Excel 2010 workbook, in a manual formulas calculation mode.
(file -> options -> formulas -> Workbook calculation -> manual)
I have some command buttons in the sheet (ActiveX controls), and I set them to move and size with cells (right click on the button -> format control -> Properties -> move and size with text).
This is since I have some rows filtered out under some conditions, and I want the buttons placed in these rows to appear and disappear as well, according to the display mode of their hosting rows.
It all goes perfectly fine, till I save he worksheet when some of the rows (hence buttons) are filtered out (i.e. not displayed).
When I re-open the file again, and expand the filtered rows, the buttons don't show. When checking their properties I see that their visible property is True, but their height is 0, and this doesn't change when I un-filter their hosting rows.
I want to emphasize again that before saving the file - both filtering and un-filtering the buttons worked well.
Would much appreciate any help here.
OK so I get the same results either with ActiveX or Form Controls. For whatever reason, it seems the control's original height does not persist beyond the save & close.
Another option would be to simply clear the AutoFilter on the Workbook's Close and Save events. However, this probably is not what you want if you like to leave some filter(s) on when you save and re-open the file. It's probably possible to save the filter parameters in a hidden sheet or by direct manipulation of the VBE/VBA, but that seems like a LOT more trouble than it's worth. Then you could re-apply the filter(s) when you re-open the workbook.
Here is what code I suggest
NOTE: I relied on the worksheet's _Calculate event with a hidden CountA formula (setting, changing, or clearing the AutoFilter will trigger this event). I put the formula in E1 just so you can see what it looks like:
Since your application relies on Calculation = xlManual then this approach will not work exactly for you but in any case, the subroutine UpdateButtons could be re-used. You would need to tie it in to another event(s) or functions in your application, as needed.
Here is the code
Option Explicit
Private Sub UpdateButtons()
'## Assumes one button/shape in each row
' buttons are named/indexed correctly and
' the first button appears in A2
Dim rng As Range
Dim shp As Shape
Dim i As Long
Application.EnableEvents = False
'## use this to define the range of your filtered table
Set rng = Range("A1:A6")
'## Iterate the cells, I figure maybe do this backwards but not sure
' if that would really make a difference.
For i = rng.Rows.Count To 2 Step -1
Set shp = Nothing
On Error Resume Next
Set shp = Me.Shapes(i - 1)
On Error GoTo 0
If Not shp Is Nothing Then
DisplayButton Me.Shapes(i - 1), Range("A" & i)
End If
Next
Application.EnableEvents = True
End Sub
Private Sub DisplayButton(shp As Shape, r As Range)
'# This subroutine manipulates the shape's size & location
shp.Top = r.Top
shp.TopLeftCell = r.Address
shp.Height = r.Height
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
MsgBox "_Change"
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
''## Assumes one button/shape in each row
'' buttons are named/indexed correctly and
'' the first button appears in A2
'Dim rng As Range
'Dim shp As Shape
'Dim i As Long
'
''## Uncomment this line if you want an annoying message every time
''MsgBox "Refreshing Command Buttons!"
'
'Application.EnableEvents = False
''## use this to define the range of your filtered table
'Set rng = Range("A1:A6")
'
''## Iterate the cells, I figure maybe do this backwards but not sure
'' if that would really make a difference.
'For i = rng.Rows.Count To 2 Step -1
' Set shp = Nothing
' On Error Resume Next
' Set shp = Me.Shapes(i - 1)
' On Error GoTo 0
'
' If Not shp Is Nothing Then
' DisplayButton Me.Shapes(i - 1), Range("A" & i)
' End If
'Next
'
'Application.EnableEvents = True
End Sub
For Another option See this article. You can re-purpose existing commands with RibbonXML customization. While this article is geared towards C# and Visual Studio it's possible to do it with the CustomUI Editor.
I had a similar problem with buttons disapearing (moving on upper left corner) when removing filters.
A solution I found was to add a row above the columns headers so that buttons were still appearing at the top of the columns but were not touching the row where filters were placed.
Adding / removing filters stop interfering with buttons' positions.
I had a similar problem where form buttons appear to work fine, but then disappear after saving and reopening the workbook. Specifically this happened when the form button where part of hidden rows (done using vba code).
Seems like a real bug, although I don't know where the link is.
By changing the form buttons to ActiveX buttons, the buttons stopped disappearing, but started moving/bunching to the top of the screen when the rows were hidden. I just added some vba to re-position the buttons (e.g. CommandButton1.Top = Range(A12:A12).Top --> moves the ActiveX command button to the 12th row).

Resources