This question already has answers here:
Assign code to a button created dynamically
(2 answers)
Closed 4 years ago.
I am trying to add an option button from the range in the Excel worksheet.
For Each Value In OptionList
Set opt = UserForm3.Controls.Add("Forms.OptionButton.1", "radioBtn" & i, True)
opt.Caption = Value
opt.Top = opt.Height * i
opt.GroupName = "Options"
UserForm3.Width = opt.Width
UserForm3.Height = opt.Height * (i + 2)
i = i + 1
Next
I want to create an event handler so that if radiobtn1 is selected while running the code from the user. Alhough I got a lot of answers, those are meant for worksheet user form.
My intention is to work on the VBA user form. Please help me with your thoughts.
There is only one type of userform, however there is [eternal] confusion surrounding the two types of controls available to Excel — exacerbated by the contrasting terminology used by different online sources. (Only the sections about ActiveX controls apply to userforms.) Perhaps I can help shed some light by putting it in words that help me understand. ☺
Overview:
There are two types of controls: Form controls and ActiveX controls:
Both types of controls can be used on worksheets but only ActiveX controls can be used on userforms.
Form controls are part of the Shapes collection (just like Drawing Objects), and thus are referred to like:
ActiveX controls are basically part of the worksheet and are therefore referred to like:
Both types of controls can be created, modified and deleted from either the worksheet, or programmatically with VBA, however, the 2 types of controls have slightly varying syntax when using VBA to refer to them.
Some sites discuss also discuss a Data Form. This is nothing more than a userform made specifically for data entry/manipulation of data, so it would've made more sense to call them (the more familiar sounding) "Data Entry Userform".
Office documentation also occasionally refers to a worksheet as a form. While this is technically correct, don't let this confuse you. Think of the word "form" as being used in a general sense:
Two Types of Controls
Form Controls
ActiveX Controls
The two look, behave, and are controlled similarly, but not identically. (List here.)
For example, let's compare the two types of Combo Boxes. In some programming languages, comparable controls are referred to as a "drop-down menu" or "drop-down list". In Excel, we have a "Form Control Combo Box", and an "ActiveX Control Combo Box":
(Click image to enlarge.)
☆ "Default name" applies to controls created manually. Controls created programmatically do not have (or require) a default name and therefore should have one assigned immediately upon creation.
(Source: my answer)
About ActiveX controls and related security concerns
An ActiveX control is an extension to the VBA Toolbox. You use ActiveX controls just as you would any of the standard built-in controls, such as the CheckBox control. When you add an ActiveX control to an application, it becomes part of the development and run-time environment and provides new functionality for your application.
An ActiveX control is implemented as an in-process server (typically a small object) that can be used in any OLE container. Note that the full functionality of an ActiveX control is available only when used within an OLE container designed to be aware of ActiveX controls.
This container type, called a control container or control object, can operate an ActiveX control by using the control’s properties and methods, and receives notifications from the ActiveX control in the form of events. The following figure demonstrates this interaction:
(Source: this and this)
See also:
Wikipedia: ActiveX
Symantec.com : Discussion of ActiveX Vulnerabilities
How-To Geek : What ActiveX Controls Are and Why They’re Dangerous
Option Buttons (Radio Buttons)
In Excel, the two types of radio buttons are actually called Option Buttons. To further confuse matters:
the default name for the form control is OptionButton1.
the default name for the ActiveX control is Option Button 1.
A good way to distinguish them is by opening the control's Properties list (on the ribbon under the Development tab, or by right-clicking the control and choosing Properties, or hitting F4), because the ActiveX control has many more options that the simpler form control.
Option buttons and checkboxes can be bound together (so only one option at a time can be selected from the group) by placing them in a shared Group Box.
Select the group box control and then hold Ctrl while selecting each of the other controls that you want to group. Right-click the group box control and choose Grouping → Group.
The first two links below are separate sets of instructions for handling each type of option button.
HANDLING CONTROL EVENTS:
Form control events (Click event only)
Form control events are only able to respond to one event: the Click event. (More info here.) Note that this section doesn't apply to userforms since they use only ActiveX controls.
To add a procedure for the Click event:
Right-click the control and choose Assign Macro...
In the 'Assign Macro` Dialog:
Select an existing procedure, and click OK, or,
Create a new procedure in the VBE by clicking New..., or,
Record a new macro by clicking Record..., or,
to Remove the assigned event, delete its name from Macro Name field and click OK.
(Click image to enlarge.)
To rename, edit or delete existing macros, hit Alt+F8 to open the Macro interface:
ActiveX control events
ActiveX controls have a more extensive list of events to which they can be set up to respond.
To assign events to ActiveX controls, right-click the control and choose View Code. In the VBE, you can paste in code, or choose specific events from the drop-down list at the top-right of the VBE window.
(Click image to enlarge.)
Control event handling on a userform:
Events can also be used in controls on userforms. Since only ActiveX controls can be placed a userform, you'll have the "more coding + more functionality" trade-off.
ActiveX controls are added to userforms the same way as they are added to a worksheet. Keep in mind that any events assigned to the userform itself (ie., background) will be "blocked" in any areas covered up by a control, so you may need to assign the same events to the controls as well as the userform.
For example, in order to make this userform respond to MouseMove anywhere on the form, the same event code was applied to the userform, textboxes, option buttons and the frame:
VBA EXAMPLES
Add/Modify/Delete a form control option button using VBA:
Sub formControl_add()
'create form control
Dim ws As Worksheet: Set ws = ActiveSheet
With ws.Shapes.AddFormControl(xlOptionButton, 25, 25, 100, 100)
.Name = "cOptionButton1" 'name control immediately (so we can find it later)
End With
End Sub
Sub formControl_modify()
'modify form control's properties
Dim ws As Worksheet: Set ws = ActiveSheet
ws.Shapes("cOptionButton1").Select
With Selection 'shapes must be Selected before changing
.Characters.Text = "wxyzabcd"
End With
End Sub
Sub formControl_delete()
'delete form control
Dim ws As Worksheet: Set ws = ActiveSheet
ws.Shapes("cOptionButton1").Delete
End Sub
Shapes.AddShape Method (Excel)
Shape Properties (Excel)
Characters Object (Excel)
Add/Modify/Delete an ActiveX command button using VBA:
Sub activexControl_add()
'create ActiveX control
Dim ws As Worksheet: Set ws = ActiveSheet
With ws.OLEObjects.Add("Forms.CommandButton.1")
.Left = 25
.Top = 25
.Width = 75
.Height = 75
.Name = "xCommandButton1" 'name control immediately (so we can find it later)
End With
End Sub
Sub activexControl_modify()
' modify activeX control's properties
Dim ws As Worksheet: Set ws = ActiveSheet
With ws.OLEObjects("xCommandButton1").Object
.Caption = "abcxyz"
.BackColor = vbGreen
End With
End Sub
Sub activexControl_delete()
' delete activeX control
Dim ws As Worksheet: Set ws = ActiveSheet
ws.OLEObjects("xCommandButton1").Delete
End Sub
OLEObjects.Add Method (Excel)
BackColor, ForeColor Properties (ActiveX Controls)
Add/Remove items from a form control combo box:
Sub ComboBox_addRemoveItems_FormControl()
Dim ws As Worksheet: Set ws = ActiveSheet
'add item to form control combo box
ActiveWorkbook.Sheets("Sheet1").Shapes("Drop Down 1").ControlFormat.AddItem "abcd"
'remove all items from from form control combo bo
ActiveWorkbook.Sheets("Sheet1").Shapes("Drop Down 1").ControlFormat.RemoveAllItems
End Sub
Add/Remove items from an ActiveX combo box:
Sub ComboBox_addRemoveItems_ActiveXControl()
Dim ws As Worksheet: Set ws = ActiveSheet
'add items to ActiveX combo box
ActiveWorkbook.Sheets("Sheet1").ComboBox1.AddItem "abcd"
'remove all items from ActiveX combo box
ActiveWorkbook.Sheets("Sheet1").ComboBox1.Clear
End Sub
More Information:
Office.com : Add a checkbox or option button (Form controls)
Office.com : Add a checkbox, option button, or toggle button (ActiveX controls)
Office.com : Overview of forms, Form controls, and ActiveX controls on a worksheet
Office.com : Enable selection through choice controls (check and list boxes)
Office.com : Add, edit, find, and delete rows by using a data form
MSDN : VBA Shape Members
MSDN : Using ActiveX Controls on Sheets (Office)
Exceldemy : How to Use Form Controls in Excel
MSDN : Using Windows Forms Controls on Excel Worksheets (Visual Studio)
Microsoft TechNet : Behaviour of ActiveX controls embedded in Office documents
Related
Currently I'm working on a userform prompting an inputbox for a range whenever the combobox dropdown button is clicked.
The problem is that whenever the range is selected (selecting a cell and then clicking ok), the userform is unselected (greys out), shows an empty dropdown list and forces me to reselect a range after I click anywhere on the workbook.
Is there any way to prevent a re selection of a range when clicking the dropdown button?
Code Below:
Private Sub ComboBox1_DropButtonClick()
Dim InputCell As Range
Set InputCell = Application.InputBox("Select Lookup Cell", "Obtain Object Range", Type:=8)
ComboBox1.Text = InputCell.Address(0, 0, external:=True)
End Sub
When I've used the RefEdit object in the past, I used the real thing (which I know has it's issues) and just used the Change event.
Perhaps you could just use the Enter event (you just have to ignore it the first time, if's it the first object that gets focus when initialized)
Resources:
Using RefEdit Controls in Excel
Dialogs - Jon Peltier
RefEdits must be placed directly on the UserForm itself. If you put a
RefEdit in a frame or on a multipage, strange things will happen,
including bizarre Excel crashes.
RefEdits must not be used on modeless forms. RefEdits on modeless
forms will result in bizarre Excel crashes.
RefEdit event procedures should be avoided. RefEdit events do not
behave reliably, and they may result in VBA errors which are difficult
to debug.
References to RefEdits must be removed. When a UserForm is added to a
VB project, Excel adds a reference to the Microsoft Forms 2.0 Object
Library. This reference is required for proper operation of the
UserForms in your project. To see what references your project has,
select the project in the Project Explorer, then select References
from the Tools menu.
Alternative to Excel’s Flaky RefEdit Control - Jon Peltier
The new approach uses a TextBox in the dialog instead of the RefEdit.
The TextBox does not interact directly with a range as does the RefEdit. Instead, when this drop button is clicked, the dialog is temporarily hidden, and an InputBox appears to solicit the user’s input.
"It may be tempting to use type 8 to indicate a range object, but there
is an obscure glitch that causes it to fail when the worksheet
contains conditional formatting conditions that use formulas in their
definitions. Fortunately using Type 0 to specify a formula works just
fine."
Cannot use keyboard shortcuts to select ranges in RefEdit control in Excel
From this source: Ozgrid
Though I'll be using custom text boxes, this could also work if anyone wants to use the combo boxes.
Private Sub ComboBox1_DropButtonClick()
Static Abort As Boolean
If Abort Then Exit Sub
Abort = False
Dim InputCell As Range
Set InputCell = Application.InputBox("Select Lookup Cell", "Obtain Object Range", Type:=8)
ComboBox1.Text = InputCell.Address(0, 0, external:=True)
Abort = True
End Sub
I'd like to insert a custom ActiveX control into a Powerpoint slide. I've created the custom control and registered it, and tested that it works. I can easily add the custom control to a UserForm, but can't add it directly to the slide (as per the other controls under Developer Tab -> Controls).
Is it possible to add the custom ActiveX control directly to the slide?
If not, is it possible to embed the UserForm directly to the slide?
Thanks!
I'm kind of guessing here, but it's worth giving it a shot. When you registered your ActiveX Control, I'm assuming you assigned a Program ID along with it, correct? If you did, then you might be able to add it as a shape object to the slide you specify. When you add a shape, you can add specific types of shapes, including OLEObjects.
For example, in the code below, I add an ActiveX ComboBox Control to Slide 1 in the Active Presentation using PowerPoint VBA. The critical thing to note is that the ProgID identifies the object being inserted.
Sub ActiveXControlAdd()
'Declare your variables.
Dim PPTPres As Presentation
Dim PPTSld As Slide
Dim PPTShp As Shape
'Grab the slide you want it on.
Set PPTPres = ActivePresentation
Set PPTSld = PPTPres.Slides(1)
'Add a shape, but make sure it's an OLEObject. Also, CLASSNAME is the ProgID!
Set PPTShp = PPTSld.Shapes.AddOLEObject(Left:=100, Top:=100, Width:=150, Height:=50, ClassName:="Forms.ComboBox.1")
'Print it out to make sure.
Debug.Print PPTShp.OLEFormat.ProgID
End Sub
Give it a try and see if that maybe fixes the issue.
If I understand, you want to insert ActiveX control to PowerPoint slide:
Go to File > Options > Customize Ribbon
On the second column, tick the "Developer" tab.
After you tick it you should see a "Developer" tab in PowerPoint; click on it.
The 3rd and 4th column is where the ActiveX controls are:
For example:
You want to insert a textbox.
You click on the icon that says "abc", next to the big "A".
Then you place it on your slide just like you would place a shape. Click & drag.
I have a pretty large template (in terms of macros) and I've created a new module that is called when the user does a specified shortcut on the keyboard.
The Macro does nothing more but call "ThisDocument.HideComboBoxes".
"HideComboBoxes" is a Sub in ThisDocument, which does the obvious: hide all combo boxes in the document.
The code works fine as long as I'm working with the template.
If I render a new document out of it (a docx file) the shortcut does not work anymore (which is kinda obvious because the ThisDocument is now empty for the document).
How do I access the template's ThisDocument from within the document or how can I hide the combo boxes from within the docx?
Here's the code for hiding the comboboxes in the template's ThisDocument:
Sub HideComboBoxes()
Me.ComboBoxConfi.Width = 1
Me.ComboBoxConfi.Height = 1
Me.ComboBoxState.Width = 1
Me.ComboBoxState.Height = 1
End Sub
Thanks in advance
You need to put the code in a "normal" module. This will require changing the calls to the ActiveX controls, which is a pain, but works.
Assuming the ActiveX controls are managed on the document surface as InlineShapes a call would look like this:
Dim cbConfi as Object 'or as MsForms.ComboBox to get Intellisense
Set cbConfi = ActiveDocument.InlineShapes([indexvalue]).OLEFormat.Object
cbConfi.Width = 1
If you don't want to rely on the index value (position of the control in the InlineShapes collection) you can select the ActiveX control and assign a bookmark to it. Or you can loop the collection of ActiveX controls, check the Type and, if it's a OLE object, check whether the Class type is MSForms.Combobox and then via OLEFormat.Object.Name whether its the right one.
I’m running Excel 2010 on Windows 7.
I have four charts on a worksheet. What I want to do is select one of the charts and then click a button to open the ‘Format Axis’ dialogue box. I found the following code online to open the dialogue box. If I select a chart and then run the code from the toolbar (Developer tab, Macros, select macro, press ‘Run’), it works well.
Sub formatXAxis1()
ActiveChart.Axes(xlCategory).Select
Application.CommandBars.ExecuteMso "ChartFormatSelection"
End Sub
The trouble I have is when the VBA script is assigned to a button. If I use a shape as the button, I get “Run-time error ‘91’: Object variable or With block variable not set”. I get the same error if I use an ActiveX Command Button. However, with a Form Control button it works as expected. The only problem with this solution is that it is not possible to change the background colour of the button so it looks out of place against the other macro calling buttons on the worksheet.
I'm guessing that in the first two cases (shape and ActiveX buttons), VBA drops or loses the chart selection when I press the button – even though the chart still appears selected on screen. Is there a fix for this, or am I doing something wrong?
For an ActiveX button, in the Properties set the property
TakeFocusOnClick
to False. That will cause Selection to keep on the chart rather than switch to the button and your code should work. The color can also be changed from the properties box, though you probably already know that.
You need to reference the chart by name. So either have 4 buttons (one for each chart), or ask the user to input the name of the chart, then:
Dim co as ChartObject
Dim c as Chart
Dim NameOfChart as String
NameOfChart = Inputbox("Enter name of chart")
Set co = ActiveSheet.ChartObjects(NameOfChart)
Set c = co.chart
c.Axes(xlCategory).Select
Application.CommandBars.ExecuteMso "ChartFormatSelection"
I am using Excel 2013. I have added an activex control to my spreadsheet. The control is a checkbox which I have named chkAD1. My spreadsheet is called "timeseries_AD".
I am trying to reference the checkbox to check its value however without any joy. I have tried the lines below,
worksheets("timeseries_AD").OleObjects("chkAD1").Value
This results in the error message "unable to get the OLEObjects property of the worksheet class".
I have read that an activex control has two names. One is the name of the shape that contains the control the other is the code name. I'm not sure which one I have changed. I clicked on my control and in the Name Box renamed it to "chkAD1". Is that the shape name or code name I have changed?
UPDATE - Apologies
Sorry the control I added is not an activex control it is actually a form control.
I tried this and it worked for me.
When I check the box I get a messagebox that says TRUE.
And when I uncheck it I get a messagebox that says FALSE
Private Sub CheckBox1_Click()
MsgBox CheckBox1.Value
End Sub