Содержание
- OLEObjects object (Excel)
- Remarks
- Example
- Methods
- Properties
- See also
- Support and feedback
- Using ActiveX Controls on Sheets
- Добавление элементов управления с помощью Visual Basic
- Использование свойств элемента управления с Visual Basic
- Использование имен элементов управления с коллекциями shapes и OLEObjects
- Поддержка и обратная связь
- OLEObjects.Add method (Excel)
- Syntax
- Parameters
- Return value
- Example
- Support and feedback
- Объект OLEObjects (Excel)
- Замечания
- Пример
- Методы
- Свойства
- См. также
- Поддержка и обратная связь
OLEObjects object (Excel)
A collection of all the OLEObject objects on the specified worksheet.
Each OLEObject object represents an ActiveX control or a linked or embedded OLE object.
An ActiveX control on a sheet has two names: the name of the shape that contains the control, which you can see in the Name box when you view the sheet, and the code name for the control, which you can see in the cell to the right of (Name) in the Properties window.
When you first add a control to a sheet, the shape name and code name match. However, if you change either the shape name or code name, the other is not automatically changed to match. The latter however, seems to have changed with Excel versions. With version 16.0 both are kept consistent and is not possible to change one of the two alone.
Example
Use the OLEObjects method of the Worksheet object to return the OLEObjects collection.
The following example hides all the OLE objects on worksheet one.
Use the Add method to create a new OLE object and add it to the OLEObjects collection. The following example creates a new OLE object representing the bitmap file Arcade.bmp and adds it to worksheet one.
The following example creates a new ActiveX control (a list box) and adds it to worksheet one.
You use the code name of a control in the names of its event procedures. However, when you return a control from the Shapes or OLEObjects collection for a sheet, you must use the shape name, not the code name, to refer to the control by name. For example, assume that you add a check box to a sheet and that both the default shape name and the default code name are CheckBox1. If you then change the control code name by typing chkFinished next to (Name) in the Properties window, you must use chkFinished in event procedures names, but you still have to use CheckBox1 to return the control from the Shapes or OLEObject collection, as shown in the following example.
Methods
Properties
See also
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
Using ActiveX Controls on Sheets
В этом разделе рассматриваются конкретные сведения об использовании элементов ActiveX на листах и листах диаграмм. Общие сведения о добавлении элементов управления и работе с ними см. в разделах Использование элементов ActiveX в документе и Создание настраиваемого диалогового окна.
При работе с элементами управления на листах учитывайте следующие моменты:
Помимо стандартных свойств, доступных для элементов ActiveX, с элементами ActiveX в Microsoft Excel можно использовать следующие свойства: BottomRightCell, LinkedCell, ListFillRange, Placement, PrintObject, TopLeftCell и ZOrder.
Эти свойства можно задать и вернуть с помощью имени элемента activeX. В следующем примере окно книги прокручивается, поэтому CommandButton1 находится в левом верхнем углу.
Некоторые методы и свойства Microsoft Excel Visual Basic отключаются при активации элемента ActiveX. Например, метод Sort нельзя использовать, когда элемент управления активен, поэтому следующий код завершается ошибкой в процедуре события нажатия кнопки (так как элемент управления по-прежнему активен после его щелчка пользователем).
Эту проблему можно обойти, активировав другой элемент на листе перед использованием свойства или метода, который завершился ошибкой. Например, следующий код сортирует диапазон:
Элементы управления книгой Microsoft Excel, внедренные в документ в другом приложении, не будут работать, если пользователь дважды щелкнет книгу, чтобы изменить ее. Элементы управления будут работать, если пользователь щелкнет книгу правой кнопкой мыши и выберет команду Открыть в контекстном меню.
При сохранении книги Microsoft Excel в формате файла книги Microsoft Excel 5.0/95 сведения об элементе управления ActiveX теряются.
Ключевое слово Me в процедуре события для элемента ActiveX на листе ссылается на лист, а не на элемент управления .
Добавление элементов управления с помощью Visual Basic
В Microsoft Excel элементы activeX представлены объектами OLEObject в коллекции OLEObjects (все объекты OLEObject также находятся в коллекции Shapes ). Чтобы программно добавить элемент ActiveX на лист, используйте метод Add коллекции OLEObjects . В следующем примере на лист 1 добавляется кнопка команды.
Использование свойств элемента управления с Visual Basic
Чаще всего код Visual Basic будет ссылаться на элементы ActiveX по имени. В следующем примере изменяется заголовок элемента управления с именем CommandButton1.
Обратите внимание, что при использовании имени элемента управления вне модуля класса для листа, содержащего элемент управления, необходимо указать имя элемента управления именем листа.
Чтобы изменить имя элемента управления, используемое в коде Visual Basic, выберите элемент управления и задайте свойство (Name) в окно свойств.
Так как элементы ActiveX также представлены объектами OLEObject в коллекции OLEObjects , можно задать свойства элемента управления с помощью объектов в коллекции. В следующем примере задается левое положение элемента управления с именем CommandButton1.
Свойства элемента управления, которые не отображаются как свойства объекта OLEObject , можно задать, возвращая фактический объект управления с помощью свойства Object . В следующем примере задается заголовок для CommandButton1.
Так как все объекты OLE также являются членами коллекции Shapes , можно использовать коллекцию для задания свойств для нескольких элементов управления. В следующем примере левая граница всех элементов управления выравнивается на листе 1.
Использование имен элементов управления с коллекциями shapes и OLEObjects
Элемент ActiveX на листе имеет два имени: имя фигуры, содержащей элемент управления, которое отображается в поле Имя при просмотре листа, и кодового имени элемента управления, которое отображается в ячейке справа от (Имя) в окно свойств. При первом добавлении элемента управления на лист имя фигуры и код совпадают. Однако при изменении имени фигуры или кодового имени другое не будет автоматически изменено на соответствие.
Имя кода элемента управления используется в именах его процедур событий. Однако при возврате элемента управления из коллекции Shapes или OLEObjects для листа необходимо использовать имя фигуры, а не код, чтобы ссылаться на элемент управления по имени. Например, предположим, что вы добавили флажок на лист и что имя фигуры по умолчанию и код по умолчанию — CheckBox1. Если затем изменить имя кода элемента управления, введя chkFinished рядом с (Name) в окно свойств, необходимо использовать chkFinished в именах процедур событий, но вам все равно придется использовать CheckBox1 для возврата элемента управления из коллекции Shapes или OLEObject, как показано в следующем примере.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
OLEObjects.Add method (Excel)
Adds a new OLE object to a sheet.
Syntax
expression.Add (ClassType, FileName, Link, DisplayAsIcon, IconFileName, IconIndex, IconLabel, Left, Top, Width, Height)
expression A variable that represents an OLEObjects object.
Parameters
Name | Required/Optional | Data type | Description |
---|---|---|---|
ClassType | Optional | Variant | You must specify either ClassType or FileName. A string that contains the programmatic identifier for the object to be created. If ClassType is specified, FileName and Link are ignored. |
FileName | Optional | Variant | You must specify either ClassType or FileName. A string that specifies the file to be used to create the OLE object. |
Link | Optional | Variant | True to have the new OLE object based on FileName be linked to that file. If the object isn’t linked, the object is created as a copy of the file. The default value is False. |
DisplayAsIcon | Optional | Variant | True to display the new OLE object either as an icon or as its regular picture. If this argument is True, IconFileName and IconIndex can be used to specify an icon. |
IconFileName | Optional | Variant | A string that specifies the file that contains the icon to be displayed. This argument is used only if DisplayAsIcon is True. If this argument isn’t specified or the file contains no icons, the default icon for the OLE class is used. |
IconIndex | Optional | Variant | The number of the icon in the icon file. This is used only if DisplayAsIcon is True and IconFileName refers to a valid file that contains icons. If an icon with the given index number doesn’t exist in the file specified by IconFileName, the first icon in the file is used. |
IconLabel | Optional | Variant | A string that specifies a label to display beneath the icon. This is used only if DisplayAsIcon is True. If this argument is omitted or is an empty string («»), no caption is displayed. |
Left | Optional | Variant | The initial coordinates of the new object, in points, relative to the upper-left corner of cell A1 on a worksheet, or to the upper-left corner of a chart. |
Top | Optional | Variant | The initial coordinates of the new object, in points, relative to the top of row 1 on a worksheet, or to the top of the chart area on a chart. |
Width | Optional | Variant | The initial width of the new object, in points. |
Height | Optional | Variant | The initial height of the new object, in points. |
Return value
An OLEObject object that represents the new OLE object.
Example
This example creates a new Microsoft Word OLE object on Sheet1.
This example adds a command button to sheet one.
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
Объект OLEObjects (Excel)
Коллекция всех объектов OLEObject на указанном листе.
Замечания
Каждый объект OLEObject представляет элемент управления ActiveX или связанный или внедренный объект OLE.
Элемент ActiveX на листе имеет два имени: имя фигуры, содержащей элемент управления, которое отображается в поле Имя при просмотре листа, и кодового имени элемента управления, которое отображается в ячейке справа от (Имя) в окно свойств.
При первом добавлении элемента управления на лист имя фигуры и код совпадают. Однако при изменении имени фигуры или кодового имени другое не будет автоматически изменено на соответствие. Последнее, однако, похоже, изменилось с версиями Excel. В версии 16.0 оба варианта поддерживают согласованность и невозможно изменить один из двух вариантов в одиночку.
Пример
Используйте метод OLEObjects объекта Worksheet , чтобы вернуть коллекцию OLEObjects .
В следующем примере все объекты OLE скрываются на одном листе.
Используйте метод Add , чтобы создать объект OLE и добавить его в коллекцию OLEObjects . В следующем примере создается новый объект OLE, представляющий точечный файл Arcade.bmp, и добавляет его на лист.
В следующем примере создается новый элемент ActiveX (поле списка) и он добавляется на первый лист.
Имя кода элемента управления используется в именах его процедур событий. Однако при возврате элемента управления из коллекции Shapes или OLEObjects для листа необходимо использовать имя фигуры, а не код, чтобы ссылаться на элемент управления по имени. Например, предположим, что вы добавили флажок на лист и что имя фигуры по умолчанию и код по умолчанию — CheckBox1. Если изменить имя кода элемента управления, введя chkFinished рядом с (Name) в окно свойств, необходимо использовать chkFinished в именах процедур событий, но по-прежнему необходимо использовать CheckBox1 для возврата элемента управления из коллекции Shapes или OLEObject, как показано в следующем примере.
Методы
Свойства
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Excel VBA — ActiveX Controls, Form Controls & AutoShapes on a Worksheet
————————————————————————————————
Contents:
Forms in Excel
ActiveX controls, Form controls & AutoShapes in an Excel Worksheet
Shape object & OLEObject object
ActiveX Controls in VBA
Add an ActiveX Control, a Form Control or an AutoShape, in Worksheet
Illustrating Form Controls, ActiveX Controls & AutoShapes:
Button (Form Control); Command Button (ActiveX Control)
Check Box — Form Control or ActiveX Control
List Box & Combo Box — Form Control / ActiveX Control
Option Button — Form Control or ActiveX Control
Toggle Button — ActiveX Control
ScrollBar & SpinButton Controls — Form Control or ActiveX Control
TextBox — ActiveX Control
Label — Form Control or ActiveX Control
Illustrating Auto Shapes, Add a connector
————————————————————————————————
You can create various types of Forms in Excel, which are documents having a standard structure & format & help to organize, capture & modify data. Type of forms which can be created in Excel include: Data Form, Worksheet containing Form controls & ActiveX controls, & UserForms in VBA. You may use a Form individually, or combine them in various manners for your suitability. In this section we explain the Shape object & OLEObject object, and illustrate using ActiveX Controls, Form controls & AutoShapes in an Excel Worksheet.
Built-in Excel Data Form
Using a Data Form is an easy way to display or enter all information in one row in a table or in a range, without scrolling or moving between columns. A Data Form is best used: (i) when your spreadsheet is too big & you constantly scroll back & forward to display & enter data; (ii) when you want to view a simple form containing text boxes labeled on column headings, wherein each text box displays the row data for each column; & (iii) when you do not need advanced form features like a list box or spin button.
Excel has a built-in Data Form which can be generated automatically for your table or range listing all the table fields: all columns headers are displayed as labels for text boxes in one dialog box; each text box displays the row data for each column upto a maximum of 32 columns; you may enter new rows, update or delete rows, scroll through the records using the scroll bar, find previous or next rows based on specified criteria or cell contents; only formula result is displayed in text box for cells with formulas; Data Form cannot be printed though you may use the PrtScr button to save an image.
Refer Image 1a: Cell J3 has been selected, and Data Form is generated by clicking on ‘Form’ button in the Quick Access Toolbar (to Add the Form button to the Quick Access Toolbar: click the arrow next to the ‘Quick Access Toolbar’ > click ‘More Commands’ > click ‘All Commands’ in the ‘Choose commands from box’ > select the ‘Form’ button > click ‘Add’ > click ‘OK’). Image 1a displays the first row data in the Data Form: to navigate through one row at a time you may use the vertical scroll arrows in the center or click the Find Prev or Find Next (clicking the scroll bar in the area between the arrows will move through 10 rows in one go); to find the next or previous row as per criteria or cell contents — click Criteria, enter criteria (say Male in the Gender text box), click Find Next, and then the next row corresponding to Male Gender will be displayed; click on New or Delete to add new row or delete existing row; to change row data — press TAB to move to the next field in the row & press SHIFT+TAB to move to the previous field, enter new content in the field or text box, press Enter and the data will be updated & you will go the next row — clicking on Restore before pressing Enter will restore the old content; click Close to close the Data Form. Note that only formula result is dsplayed in text box for BMI column header whose cells have formulas, wherein the formula cannot be changed using the data form. When you enter Criteria, you may use the following wildcard characters: ? (question mark) > to find any single character viz. T?m finds both Tim & Tom; * (asterik) > to find any number of characters viz. *Active finds both InActive and VeryActive; ~ (tilde) followed by ?, *, or ~ > to find a question mark, asterik or tilde viz. When~? finds When?.
UserForms in Excel VBA
UserForm is a customized user interface (viz. custom dialog box), developed in VBA. It enables a user to interact, using a Form, in an organized and logical manner, to make data entry or for data retrieval with an Excel worksheet or to run a VBA application. UserForm acts as a container in which you add multiple ActiveX controls, each of which has a specific use and associated properties. By itself, a UserForm will not be of much use unless ActiveX controls are added to it which are the actual user-interactive objects. Refer our separate section on Userforms for detailed illustration.
ActiveX controls, Form controls & AutoShapes in an Excel Worksheet
Another type of form is a worksheet: you can enter, format & view data in worksheet cells which can also be used as text boxes or labels by adjusting their height / width, so as to function as a data form; a worksheet can be used as an advanced data form by using its various built-in features which behave like controls, viz. comments, data validation, hyperlinks, background images, conditional formatting, embedded charts, AutoFilter, etc.
Two types of controls are available in Excel — Form controls & ActiveX Controls. Besides these controls, you can also add objects from the Drawing tools, like AutoShapes, WordArt, SmartArt graphic or text boxes. These controls & drawing tools add flexibility to using the worksheet as they can be linked to & work in tandem with worksheet cells — a check box control can be used to make multiple selections, an option button control allows to choose a single option from within a set of mutually exclusive choices, a spin button control facilitates to enter a number, & so on. These controls & objects can be displayed with associated labels / text & independent of row or column outlines / sizes, these may be linked to worksheet cells with our without using vba code, and can float freely or else move & resize with cells, for example, in respect of a command box control you may want to keep it the same size & in a specific location always so that when its underlying cells’ size changes or cells are moved, the command box retains its size & position.
Form Controls
Form controls are used to reference & interact with cell data in a worksheet — they are used to easily place values in worksheet cells, without programming, and they facilitate to compel users choose from defined options. VBA code is not required to use Form controls, but you can assign a macro to a control so that on clicking the control the macro will be executed. Form controls can also be added to chart sheets, but not to UserForms or to control events. For example, you may link a worksheet cell to a spin button, so that clicking on the up arrow will increase the value (increment a number, time or date) in the linked cell while clicking on the down arrow will decrease the value — this will obviate the need for manual entry in the cell. The Form controls — ‘Text Field’, ‘Combo List — Edit’, ‘Combo Drop-Down — Edit’, ‘Run Dialog’ — can only be used in Excel version 5.0 dialog sheets & are not available in Excel 2007. The various Form controls are illustrated later in this section.
ActiveX Controls
ActiveX controls can be used with VBA code or without, either directly on worksheets, while some can be used only on VBA UserForms. ActiveX controls offer more flexibility as compared to Form controls as they have numerous properties which can be used to customize their functionality, appearance, fonts & other characteristics.
ActiveX controls have associated event procedures which are triggered on clicking the control. ActiveX controls can be used to control different events, so that you can write macros to execute the associated events. You can execute different actions specific to the option selected by the user to interact with the control. You cannot assign a macro to ActiveX controls similar to Form controls wherein clicking the control executes the macro. ActiveX controls cannot be added to chart sheets or to XLM macro sheets. ActiveX controls contained in your computer include Calendar Control 12.0 & Windows Media Player, as installed by Excel or other programs.
In Excel 2007 Form Controls & ActiveX Controls are available in the Controls group on the Developer tab of the Ribbon (Refer Image 1b), while in earlier versions they were available on toolbars.
Objects from the Drawing tools
In Excel 2007, under the Insert tab on the ribbon, you can insert an Object, Shape, Picture, SmartArt graphic, Chart, Text Box, WordArt, etc. in a worksheet. Right click on the object, shape or graphic you have inserted, and select Assign Macro which opens the Assign Macro dialog box from where you can select and assign a macro to the object. In this section, we limit our discussion to AutoShapes (we have a separate section which deals with Charts in detail). You can select from a set of ready-made shape types for an AutoShape object in vba, as specified in MsoAutoShapeType Enumeration, for use in your worksheet. VBA allows you to add shapes & objects which can be manipulated & formatted by resizing or rotating, adding text or caption & setting font, changing color, or adding 3D effects such as beveling & shadows, and assigning macros.
Shape object & OLEObject object
A Shape object represents an object in the drawing layer, such as an AutoShape, freeform, OLEobject or picture. Every excel worksheet & chart sheet & excel chart has a drawing layer upon which drawing objects are placed. Both the Worksheet object & the Chart object both have a Shapes property that returns a Shapes collection ie. the Shapes object, which contains all the Shape objects in the worksheet or in the chart sheet. The you have the ShapeRange collection (ie. ShapeRange object), which represents a subset of shapes on a document — a ShapeRange object can contain a single shape, or a few shapes (viz. first, third & fifth shape out of a total of 8 shapes in a sheet), or it could represent all shapes in a document. The ShapeRange object allows you to set the properties of a subcollection of all Shape objects. We have now discussed 3 objects: (i) Shape object; (ii) Shapes object; & (iii) ShapeRange object.
An OLEObject object represents an ActiveX control or a linked or embedded OLE object on a worksheet. The OLEObjects collection (ie. OLEObjects Object) contains all the OLEObject objects on a single worksheet. Use the Worksheet.OLEObjects method to return either a single OLE object (an OLEObject ) or a collection of all OLE objects (an OLEObjects Object) — Syntax: Worksheet.OLEObjects(Index), where Index is the name or number of the OLE object. Use the OLEObjects.ShapeRange Property to return a ShapeRange object which represents the specified object or objects — a subset of shapes which can be a single shape, or a few shapes (viz. first, third & fifth shape out of a total of 8 shapes in a sheet), or it could represent all shapes. Note: OLE objects do not support many changes which can be made through ShapeRange. In Excel VBA, ActiveX controls are represented by OLEObject objects in the OLEObjects collection, so that ActiveX control properties can be set using the properties of an OLEObject object, but the OLEObject object is not used for Form Controls.
OLE — Object Linking and Embedding — is used to make content that is created in one program (ex. Microsoft Office Word) available in another program (ex. Microsoft Office Excel). OLE is supported by many different programs — only programs that are installed on your computer and which support OLE objects appear in the Object type box. Information may be copied as either a linked object or an embedded object — the prime difference between the two is where the data is stored & how the object is updated after it is placed in the destination file. Embedded objects are stored in the workbook in which they are inserted, & are not updated. Linked objects remain as separate files, & can be updated.
Shape.Type Property & Shape.FormControlType Property:
Use the Type Property of the Shape object to set or return the Shape Type, as per constants / values specified in the MsoShapeType Enumeration, Ex. the MsoShapeType constant msoFormControl indicates a Form Control, constant msoOLEControlObject indicates an OLE control object (ActiveX Control), and so on.
There is another property — FormControlType Property of the Shape object — which returns (read-only) the Control Type for a Shape object (per XlFormControl Enumeration) & this property is not valid for ActiveX controls but used only where the Shape.Type Property returns msoFormControl. Ex. the XlFormControl constant xlCheckBox represents a Check Box, constant xlListBox represents a List Box, and so on.
MsoShapeType Enumeration | XlFormControl Enumeration | |||||
MsoShapeType | Value | Description | XlFormControl | Value | Description | |
msoAutoShape | 1 | AutoShape | xlButtonControl | 0 | Button | |
msoCallout | 2 | Callout | xlCheckBox | 1 | Check box | |
msoChart | 3 | Chart | xlDropDown | 2 | Combo box | |
msoComment | 4 | Comment | xlEditBox | 3 | Text box | |
msoFreeform | 5 | Freeform | xlGroupBox | 4 | Group box | |
msoGroup | 6 | Group | xlLabel | 5 | Label | |
msoEmbeddedOLEObject | 7 | Embedded OLE object | xlListBox | 6 | List box | |
msoFormControl | 8 | Form control | xlOptionButton | 7 | Option button | |
msoLine | 9 | Line | xlScrollBar | 8 | Scroll bar | |
msoLinkedOLEObject | 10 | Linked OLE object | xlSpinner | 9 | Spinner | |
msoLinkedPicture | 11 | Linked picture | ||||
msoOLEControlObject | 12 | OLE control object | ||||
msoPicture | 13 | Picture | ||||
msoPlaceholder | 14 | Placeholder | ||||
msoTextEffect | 15 | Text effect | ||||
msoMedia | 16 | Media | ||||
msoTextBox | 17 | Text box | ||||
msoScriptAnchor | 18 | Script anchor | ||||
msoTable | 19 | Table | ||||
msoCanvas | 20 | Canvas | ||||
msoDiagram | 21 | Diagram | ||||
msoInk | 22 | Ink | ||||
msoInkComment | 23 | Ink comment | ||||
msoIgxGraphic | 24 | SmartArt graphic | ||||
msoShapeTypeMixed | -2 | Mixed shape type |
Sub Shape_Type_FormControlType()
‘returns 12 indicating an OLE control object (MsoShapeType constant of msoOLEControlObject)
MsgBox Sheets(«Sheet1»).Shapes(«OptionButton1»).Type
‘returns the message «Check Box Form Control», indicating the shape is a Form Control & is a Check Box
If Sheets(«Sheet2»).Shapes(«Check Box 1»).Type = msoFormControl Then
If Sheets(«Sheet2»).Shapes(«Check Box 1»).FormControlType = xlCheckBox Then MsgBox «Check Box Form Control»
End If
End Sub
Example: for Auto Shapes, illustrating Shapes object, Shape object & ShapeRange object
Sub AutoShape_ShapesObj_ShapeObj_ShapeRangeObj()
‘illustrating Auto Shapes — Shapes object, Shape object & ShapeRange object
‘Sheet1 contains 7 auto shapes, in this order: Rectangle 1, Rectangle 2, Oval 1, Rounded Rectange 1, Triangle 1, Oval 2, Triangle 2
Dim ws As Worksheet, shp As Shape
Set ws = Sheets(«Sheet1»)
‘———————————
‘refer Shapes collection ie. Shapes object
‘returns 7 (there are seven shapes in the collection)
MsgBox ws.Shapes.Count
‘———————————
‘refer each Shape object
For Each shp In ws.Shapes
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
shp.Placement = xlFreeFloating
Next
‘———————————
‘ShapeRange object
‘use the Range property to return multiple number of shapes — return a set of Shapes by specifying Name or Index Number — Shapes.Range(index)
‘using the Array function to construct an array of index numbers — set the fill forecolor for shapes one & four (Rectangle 1 & Rounded Rectange 1)
ws.Shapes.Range(Array(1, 4)).Fill.Solid
ws.Shapes.Range(Array(1, 4)).Fill.ForeColor.RGB = RGB(255, 0, 0)
‘using the Array function to construct an array of names — set the height for shapes named Rectangle 2 & Triangle 1 (shapes 2 & 5)
ws.Shapes.Range(Array(«Rectangle 2», «Triangle 1»)).Height = 20
‘for a single member of the collection, it is easier to use the Item method than using the Range property — set caption / text for the third shape (Oval 1)
ws.Shapes(3).TextFrame.Characters.Text = «Oval Shape«
‘activate sheet
ws.Activate
‘select shapes sixth & seventh (Oval 2, Triangle 2)
ActiveSheet.Shapes.Range(Array(6, 7)).Select
‘using the ShapeRange property of the Selection object to return all shapes in the selection
ActiveWindow.Selection.ShapeRange.Fill.Solid
ActiveWindow.Selection.ShapeRange.Fill.ForeColor.RGB = RGB(255, 255, 0)
‘return a single shape (seventh shape — Triangle 2) in the selection, by using Selection.ShapeRange(index), where index is the shape name or the index number
ActiveWindow.Selection.ShapeRange(2).TextFrame.Characters.Text = «Triangle«
End Sub
Example: for Form Controls, illustrating Shapes object, Shape object & ShapeRange object
Sub FormControls_ShapesObj_ShapeObj_ShapeRangeObj()
‘illustrating Form Controls — Shapes object, Shape object & ShapeRange object
‘Sheet1 contains 5 Form Controls, in this order: Button 1, Check Box 1, Option Button 1, Scroll Bar 1, Label 1
Dim ws As Worksheet, shp As Shape
Set ws = Sheets(«Sheet1»)
‘———————————
‘refer Shapes collection ie. Shapes object
‘returns 5 (there are seven shapes — Form Controls — in the collection)
MsgBox ws.Shapes.Count
‘———————————
‘refer each Shape object
For Each shp In ws.Shapes
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
shp.Placement = xlFreeFloating
Next
‘———————————
‘ShapeRange object
‘use the Range property to return multiple number of shapes — return a set of Shapes by specifying Name or Index Number — Shapes.Range(index)
‘using the Array function to construct an array of index numbers — set the Left property for shapes one & four (Button 1 & Scroll Bar 1)
ws.Shapes.Range(Array(1, 4)).Left = 25
‘using the Array function to construct an array of names — set the height for shapes named Check Box 1 & Option Button 1 (shapes 2 & 3)
ws.Shapes.Range(Array(«Check Box 1», «Option Button 1»)).Height = 20
‘for a single member of the collection, it is easier to use the Item method than using the Range property — set caption / text for the third shape (Option Button 1)
ws.Shapes(3).TextFrame.Characters.Text = «SelectOption«
‘activate sheet
ws.Activate
‘select shapes second & third (Check Box 1 & Option Button 1)
ActiveSheet.Shapes.Range(Array(2, 3)).Select
‘using the ShapeRange property of the Selection object to return all shapes in the selection — set a solid fill forecolor
ActiveWindow.Selection.ShapeRange.Fill.Solid
ActiveWindow.Selection.ShapeRange.Fill.ForeColor.RGB = RGB(255, 0, 0)
‘return a single shape (third shape — Option Button 1) in the selection, by using Selection.ShapeRange(index), where index is the shape name or the index number
‘set Option Button’s border line: as dash-dash-dot, thickness of 2 pts & color green
ActiveWindow.Selection.ShapeRange(2).Line.DashStyle = msoLineDashDotDot
ActiveWindow.Selection.ShapeRange(2).Line.Weight = 2
ActiveWindow.Selection.ShapeRange(2).Line.ForeColor.RGB = RGB(0, 255, 0)
End Sub
Example: for ActiveX Controls, illustrating Shapes object, Shape object & ShapeRange object
Sub ActiveXControls_OLEObjects_OLEObject_ShapeRangeObject()
‘illustrating ActiveX Controls — OLEObjects object, OLEObject object & ShapeRange object
‘Sheet1 contains 7 OLEObjects, in this order: ComboBox1, ListBox1, CommandButton1, OptionButton1, CheckBox1, SpinButton1, CommandButton2
Dim ws As Worksheet, obj As OLEObject
Set ws = Sheets(«Sheet1«)
‘Count the no. of OLEObjects in the OLEObjects collection — returns 7
MsgBox ws.OLEObjects.Count
‘refer each OLEObject object in worksheet
For Each obj In ws.OLEObjects
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
obj.Placement = xlFreeFloating
Next
‘Set the height of the OLEObject named CommandButton2
ws.OLEObjects(«CommandButton2»).Height = 30
‘———————————
‘ShapeRange object — OLE objects do not support many changes which can be made through ShapeRange
‘activate sheet
ws.Activate
‘select OLEObjects third & seventh (CommandButton1, CommandButton2)
ActiveSheet.OLEObjects(3).Select (True)
ActiveSheet.OLEObjects(7).Select (False)
‘using the ShapeRange property of the Selection object to return all OLEObjects in the selection — set shadow
ActiveWindow.Selection.ShapeRange.Shadow.Visible = True
‘using the ShapeRange property of the Selection object to return all OLEObjects in the selection — set height, in points
ActiveWindow.Selection.ShapeRange.Height = 20
‘return a single OLEObject (seventh OLEObject — CommandButton2) in the selection, by using Selection.ShapeRange(index), where index is the shape name or the index number
‘set the distance, in points, from the top edge of the object to the top of worksheet’s row 1
ActiveWindow.Selection.ShapeRange(2).Top = 270
End Sub
ActiveX Controls in VBA
By default, a control’s name (ie. code name) is based on its type ex. default name of a CommandButton is CommandButton1, second CommandButton will be CommandButton2, & so on. Every control name should be unique in a worksheet. An ActiveX control’s name is visible at the top of the Properties window (in the drop-down list where control is selected) where on the right is the control type (ex. CommandButton) and on its left is the name of the control (ex. CommandButton1). The control name (ie. CommandButton1) can be viewed & changed in the sheet’s Name box and also in the cell to the right of (Name) in the Properties window. You may also change the control name in code, using its Name property. Note that control name is different from its Caption, which is the text that may appear on the control.
ActiveX controls can be referred by name — the control name should be qualified with the sheet name when used from a module outside the sheet that contains the control. Control name is used to return the control from the Shapes or OLEObject collection ex. Sheets(«Sheet1»).OLEObjects(«CommandButton1»).Top = 25 or Sheets(«Sheet1»).Shapes(«CommandButton1»).Height = 20. Names of event procedures also correspond to the control’s name (ex. CommandButton1_Click).
ActiveX controls have associated event procedures which are triggered on clicking the control (you cannot assign any arbitrary macro to ActiveX controls like you do to Form controls). Event-handler procedures must be located in the code module of the object (viz. worksheet, UserForm) containing the control, or written in class modules. On top of the code module, there are two drop-down boxes — selecting the control on the left will display the events on the right which are supported for that control. For example, a CommandButton control generates a Click event for which an event-handler sub procedure can be written as follows viz. clicking the CommandButton control (control name CommandButton1) will enter «Hello» in cell A1 of the sheet which contains the control & return this text in a message box:
Private Sub CommandButton1_Click()
Range(«A1»).Value = «Hello«
MsgBox Range(«A1»).Value
End Sub
Accessing ActiveX Control Properties in VBA
Note: All illustrations below relate to the ActiveX control of CommandButton named «CommandButton1».
In VBA code, ActiveX controls can be referred by name & you may thus set the control properties, for example, to set the mouse pointer for CommandButton named «CommandButton1»:
Sheets(«Sheet1»).CommandButton1.MousePointer = fmMousePointerIBeam.
In Excel VBA, ActiveX controls are represented by OLEObject objects in the OLEObjects collection, so that ActiveX control properties can be set using the properties of an OLEObject object, for example:
Sheets(«Sheet1»).OLEObjects(«CommandButton1»).Top = 25 or Sheets(«Sheet1»).OLEObjects(«CommandButton1»).BottomRightCell.Interior.Color = RGB(255, 255, 0).
If the control property is listed in the Object Browser (in VBE, click View & then click Object Browser) under the class OLEObject, then you may use the OLEObject from the OLEObjects collection object, to set the property, otherwise (if the property is not listed under the OLEObject class in the Object Browser), then you must return the actual control object by using the Object property of the OLEObject object, for example to set the BackColor or the Caption property:
Sheets(«Sheet1»).OLEObjects(«CommandButton1»).Object.BackColor = RGB(255, 255, 0) or Sheets(«Sheet1»).OLEObjects(«CommandButton1»).Object.Caption = «Click to Run«.
Because an OLEObject object is also a member of the Shapes collection, many ActiveX control properties can be set using the properties of a Shape object, ex.
Dim sh As Shape
‘set sh to an existing CommandButton ActiveX control
Set shp = Sheets(«Sheet4»).Shapes(«CommandButton1»)
‘Type Property can be used only with the Shape object
If shp.Type = msoOLEControlObject Then
shp.Height = 26
shp.Placement = xlFreeFloating
shp.Locked = True
End If
Add an ActiveX Control, a Form Control or an AutoShape, in Worksheet
Add a new OLE object to an Excel sheet
Use the Add Method of the OLEObjects object, to add a new OLEObject to a sheet — this method returns an OLEObject representing the new OLE object. Syntax: OLEObjects.Add(ClassType, FileName, Link, DisplayAsIcon, IconFileName, IconIndex, IconLabel, Left, Top, Width, Height). All arguments are optional to specify. It is necessary to specify either the ClassType argument — which specifies the programmatic identifier (see below), as a string value, for the new object being added — or the FileName argument — which specifies the file name, as a string value, that is used to add the new object. Specifying the ClassType argument will ignore the FileName & Link arguments. Setting the Link argument to True will link the new object to the file whose FileName is specified whereas the False (default) setting will add the new object as a copy of the file without linking.
The new object will display as an icon or picture by setting the DisplayAsIcon argument to True, & in this case you can specify the icon by using the arguments of IconFileName & IconIndex. Only when the DisplayAsIcon argument is set to True, can you use the IconFileName argument to specify the file name containing the icon to be displayed & omitting this argument will display the default OLE class icon. Only when the DisplayAsIcon argument is set to True & the IconFileName argument specifies a valid file which contains icon(s), you can use the IconIndex argument to specify the number of the icon in the file & on non-existence of that index number the file’s first icon is used. Only when the DisplayAsIcon argument is set to True, can you use the IconLabel argument for specifying a string value to display a caption (or label) under the icon, & omitting this argument or setting it as an empty string («») will not display any caption.
The Left & Top arguments specify the distance of the new object, in points, from the left edge of column A or from the top of row 1 on a worksheet respectively (or the distance from the left edge / top edge of a chart). The Width & Height arguments specify the width & height of the new object, in points.
OLE programmatic identifier — also called a ProgID — is used to create an Automation object. The following is a list OLE programmatic identifiers for ActiveX controls:
OLE programmatic identifier | |
Below control is created | By using the below ProgID |
CheckBox | Forms.CheckBox.1 |
ComboBox | Forms.ComboBox.1 |
CommandButton | Forms.CommandButton.1 |
Frame | Forms.Frame.1 |
Image | Forms.Image.1 |
Label | Forms.Label.1 |
ListBox | Forms.ListBox.1 |
MultiPage | Forms.MultiPage.1 |
OptionButton | Forms.OptionButton.1 |
ScrollBar | Forms.ScrollBar.1 |
SpinButton | Forms.SpinButton.1 |
TabStrip | Forms.TabStrip.1 |
TextBox | Forms.TextBox.1 |
ToggleButton | Forms.ToggleButton.1 |
Example: add an ActiveX control, check box to Sheet1 — return an OLEObject representing the new OLE object:
Dim objChBx As OLEObject
Set objChBx = Sheets(«Sheet1″).OLEObjects.Add(ClassType:=»Forms.CheckBox.1«, DisplayAsIcon:=False, Left:=20, Top:=20, Width:=100, Height:=20)
MsgBox objChBx.Name
‘TypeName Function returns the data-type about a variable — TypeName(varname)
‘returns CheckBox — Object Property of the OLEObject returns a OLE Automation object associated with this OLE object
MsgBox TypeName(objChBx.Object)
You may also use the AddOLEObject Method of the Shapes object to add a new OLEObject to a sheet — this method returns a Shape object representing the new OLE object. Syntax: Shapes.AddOLEObject(ClassType, Filename, Link, DisplayAsIcon, IconFileName, IconIndex, IconLabel, Left, Top, Width, Height). All arguments are optional to specify & work similar to the Add Method of the OLEObjects object, as explained above.
Example: add an ActiveX control, check box to Sheet1 — return a Shape Object representing the new OLE object:
Dim shChkBx As Shape
Set shChkBx = Sheets(«Sheet1″).Shapes.AddOLEObject(ClassType:=»Forms.CheckBox.1«, DisplayAsIcon:=False, Left:=20, Top:=20, Width:=100, Height:=20)
MsgBox shChkBx.Name
‘Type Property can be used only with the Shape object
‘returns 12 — constant msoOLEControlObject indicating an OLE control object (ActiveX Control)
MsgBox shChkBx.Type
Create a new Form Control
Use the Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height). All arguments are necessary to be specified. The Type argument specifies the type of the form control as per constants in the XlFormControl Enumeration. The Left & Top arguments specify the distance of the new object, in points, from the left edge of column A or from the top of row 1 on a worksheet respectively (or the distance from the left edge / top edge of a chart). The Width & Height arguments specify the width & height of the new object, in points.
Add a new AutoShape
Use the Shapes.AddShape Method to Add a new AutoShape — this returns a Shape object that representing the new AutoShape — Syntax: Shapes.AddShape(Type, Left, Top, Width, Height). All arguments are necessary to specify. The Type argument specifies the shape type per the MsoAutoShapeType Enumeration. The Left argument specifies the distance of the left edge of the AutoShape’s bounding box, in points, from the left edge of the document. The Top argument specifies the distance of the top edge of the AutoShape’s bounding box, in points, from the top edge of the document. The Width & Height arguments specify the width & height of the AutoShape’s bounding box, in points.
MsoAutoShapeType Enumeration: msoShape16pointStar (value 94 — 16pointStar), msoShapeBalloon (value 137 — Balloon), msoShapeCube (value 14 — Cube), msoShapeDiamond (value 4 — Diamond), msoShapeDownArrow (value 36 — block arrow pointing down), msoShapeRightArrow (value 33 — block arrow pointing right), msoShapeLeftRightArrow (value 37 block arrow with arrowheads that point both left & right), msoShapeHeart (value 21 — Heart), msoShapeHexagon (value 10 — Hexagon), msoShapeIsoscelesTriangle (value 7 — IsoscelesTriangle), msoShapeOval (value 9 — Oval), msoShapeRectangle (value 1 — Rectangle), and so on.
To change the AutoShape type (other than a line, freeform drawing, or connector), set the AutoShapeType Property of the Shape object (Syntax: Shape.AutoShapeType) using the MsoAutoShapeType Enumeration. The shape will retain its size, color & other attributes on changing its type.
Illustrating Form Controls, ActiveX Controls & AutoShapes
Button (Form Control); Command Button (ActiveX Control)
A Button (Form Control) or a Command Button (ActiveX Control) is typically used to execute a macro when clicked by a user. You can assign a macro to the Button (Form Control) but cannot assign a macro to ActiveX controls similar to Form controls. CommandButton (ActiveX control) can have associated event procedures which are triggered on clicking the control.
CommandButton (ActiveX control) can be used to control different events, so that you can write macros to execute the associated events. You can execute different actions specific to the option selected by the user to interact with the control: you may write a macro associated with the Click event of the CommandButton so that clicking on the CommandButton will run the code which is attached to the Click event or you can insert the name of a macro to be run on clicking the CommandButton; similarly you may write a separate macro associated with another event of the CommandButton which will be executed likewise. To write a macro associated with the Click event of the CommandButton — in VBE (Visual Basic Editor) select the name of the CommandButton (in the code module of the worksheet containing the control) from the top-left dropdown of the code window and then select Click from the top-right dropdown.
CommandButton (ActiveX control) offers more flexibility as compared to Button (Form control), having numerous properties which can be used to customize its functionality, appearance, fonts & other characteristics, as illustrated by separate examples of Button & CommandButton below:
Example: Use Shapes.AddFormControl Method to create an Excel Form Control (Button) — this returns a Shape object representing the new control — refer Image 2a
Sub FormControl_Button_Shape_Properties()
‘use Shapes.AddFormControl Method to create an Excel Form Control (Button) — this returns a Shape object representing the new control — refer Image 2a
Dim shpBtn As Shape, rng As Range
Set rng = Sheets(«Sheet1»).Range(«A2»)
‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property
rng.ColumnWidth = 15
‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.
rng.RowHeight = 20
‘for an already existing Form Control shape — Button, with the name «Button 1»
‘Set shpBtn = Sheets(«Sheet1»).Shapes(«Button 1»)
‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):
‘set object variable to the newly added Button Form control — position & size the Button with the cell assigned to the rng variable
Set shpBtn = Sheets(«Sheet1«).Shapes.AddFormControl(Type:=xlButtonControl, Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height)
With shpBtn
‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).
.AlternativeText = «Click To Run«
‘set a String value as object’s name
.Name = «Button 1«
‘shape will not retain its original proportions when it is resized
.LockAspectRatio = msoFalse
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
‘reset shape height & width
.Width = rng.Width
.Height = rng.Height
‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the NextStep macro
.OnAction = «NextStep«
‘TextFrame Property returns a TextFrame object which contains the alignment & anchoring properties for a shape — valid for only a shape having a text frame
‘this property is valid for Button (Form Control)
With .TextFrame
.HorizontalAlignment = xlHAlignCenter
.VerticalAlignment = xlVAlignDistributed
.Characters.Text = «ClickButton»
‘to set internal margins:
‘.AutoMargins = False
‘.MarginLeft = 0.25
‘.MarginRight = 0.1
‘.MarginTop = 0.2
‘.MarginBottom = 0.15
With .Characters(Start:=1, Length:=5).Font
.Name = «Arial«
.Bold = True
.ColorIndex = 3
.Size = 10
.Italic = True
End With
With .Characters(Start:=6, Length:=6).Font
.Name = «Calibiri«
.Bold = True
.Size = 10
.ColorIndex = 5
.Italic = False
.Underline = True
End With
End With
‘wrt to the cell which is under the upper-left corner of the object — set one cell below this
With .TopLeftCell.Offset(1, 0)
‘enter cell address in the cell
.Value = .Address
‘set cell color to green
.Interior.Color = RGB(0, 255, 0)
End With
End With
End Sub
Example: Add a new OLEObject to a sheet — ActiveX control (CommandButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 2b
Sub ActiveXControl_CommandButton_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (CommandButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 2b
‘OLEObject is not used for Form Controls
Dim objCmdBtn As OLEObject, shpBtn As Shape
Dim ws As Worksheet, rng As Range
Set ws = Sheets(«Sheet1«)
ws.Activate
Set rng = Range(«A2«)
‘delete ActiveX Control CommandButton objects
For Each objCmdBtn In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objCmdBtn.Object) = «CommandButton» Then objCmdBtn.Delete
Next objCmdBtn
‘delete Form Control Button objects
For Each shpBtn In ActiveSheet.Shapes
If shpBtn.Type = msoFormControl Then
If shpBtn.FormControlType = xlButtonControl Then shpBtn.Delete
End If
Next shpBtn
‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property
rng.ColumnWidth = 15
‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.
rng.RowHeight = 20
‘for an already existing ActiveX control, with the name «CommandButton1»
‘Set objCmdBtn = ws.OLEObjects(«CommandButton1»)
‘Use the Add Method of the OLEObjects object, to add a new OLEObject to a sheet — this method returns an OLEObject representing the new OLE object
‘set object variable to the newly added command button ActiveX control — position & size the CommandButton with the cell assigned to the rng variable
Set objCmdBtn = ws.OLEObjects.Add(ClassType:=»Forms.CommandButton.1«, DisplayAsIcon:=False, Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height)
With objCmdBtn
‘set a String value as object’s name
.Name = «CommandButton1»
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
‘enable the object
.Enabled = True
‘returns the index number of the object within the collection of similar objects
MsgBox .Index
‘reset left & right distance of command button relative to the worksheet’s left & top edge
‘.Left = 50
‘.Top = 50
‘reset size of command button
‘.Height = 25
‘.Width = 35
‘set shadow
.Shadow = True
‘wrt to the cell which is under the upper-left corner of the object — set cell on its right
With .TopLeftCell.Offset(0, 1)
‘enter cell address in the cell
.Value = .Address
‘set cell color to green
.Interior.Color = RGB(0, 255, 0)
End With
‘Object Property of the OLEObject returns a OLE Automation object associated with the OLE object (objCmdBtn)
With .Object
.WordWrap = True
.MousePointer = fmMousePointerCross
‘load a picture into ActiveX control, using the LoadPicture Function — specify filename & address of image to be loaded
.Picture = LoadPicture(«C:UsersamitDocumentsPhotosDollar.jpg«)
.PicturePosition = fmPicturePositionAboveCenter
‘remove picture
.Picture = LoadPicture(«»)
.Caption = «Click«
‘set back color to yellow
.BackColor = RGB(255, 255, 0)
‘set font color to blue
.ForeColor = RGB(0, 0, 255)
‘for BackStyle, use fmBackStyleOpaque or fmBackStyleTransparent
.BackStyle = fmBackStyleOpaque
With .Font
.Name = «Arial«
.Bold = True
.Size = 10
.Italic = False
.Underline = False
End With
End With
End With
End Sub
Check Box — Form Control or ActiveX Control
With Check Box, user can select multiple options at a time on a worksheet or in a group box, by selecting each Check Box against which an option is available. CheckBox can be used in a singular manner viz. a single Check Box can be selected or deselected (by clicking itself) indicating whether an option is to be exercised or not. The Value property of a CheckBox indicates whether it is selected or not. A True value indicates that the CheckBox is selected, False indicates that it is cleared; and the Null value indicates that it is neither selected nor cleared, and the CheckBox will appear shaded in this case. The value of TripleState property should be set (can be set either in the Properties window or by using a macro or vba code) to True for the CheckBox to have a Null value. Option Buttons on the other hand are used in multiples viz. two or more, to indicate selection of mutually exculsive options — Option Button gets deselected only on selection of another Option Button and not by clicking itself.
Below we illustrate: (i) a Form Control Check Box & and assign it to a Macro; and (ii) an ActiveX Control CheckBox & a Macro associated with the Click event of this CheckBox.
Example: Form Control Check Box(es) & Macro to which they are assigned:
(1) Add a Form Control Check Box with the CheckBoxes.Add Method, set properties for the Form control (CheckBox) object — Refer Image 3a
Sub FormControl_CheckBox_Shape_Properties_1()
‘Add a Form Control Check Box with the CheckBoxes.Add Method, set properties for the Form control (CheckBox) object — Refer Image 3a
Dim shpChBx As Shape, ws As Worksheet, rng As Range, objChBx As OLEObject
Set ws = Sheets(«Sheet1»)
ws.Activate
‘————————
‘a quick way of adding multiple checkboxes (Form Control) in a worksheet & then deleting:
‘Dim cell As Range, rng As Range
‘Set rng = Range(«J5:J10»)
‘Set ws = Sheets(«Sheet4»)
‘ws.Activate
‘For Each cell In rng
‘With ws.CheckBoxes.Add(cell.Left, cell.Top, cell.Width, cell.Height)
‘.Characters.Text = cell.Address
‘End With
‘Next
‘ws.CheckBoxes.Delete
‘————————
Set rng = ws.Range(«B2»)
‘delete ActiveX Control CheckBox objects
For Each objChBx In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objChBx.Object) = «CheckBox» Then objChBx.Delete
Next objChBx
‘delete Form Control CheckBox objects
For Each shpChBx In ActiveSheet.Shapes
If shpChBx.Type = msoFormControl Then
If shpChBx.FormControlType = xlCheckBox Then shpChBx.Delete
End If
Next shpChBx
‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property
rng.ColumnWidth = 10
‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.
rng.RowHeight = 15
‘add a check box Form control — position & size the Check Box with the cell assigned to the rng variable
ws.CheckBoxes.Add(Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height).Select
With Selection
‘set a String value as object’s name
.Name = «Check Box 1«
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
.Display3DShading = False
‘True (for Enabled Property) indicates that the control can be accessed through a vba code & respond to user-generated events (ie. the user can interact with the control by using mouse, keystrokes, accelerators, or hotkeys) — enable the object
.Enabled = True
‘check box will be printed when the document is printed
.PrintObject = True
.linkedCell = rng.Address
‘wrt to the cell which is under the upper-left corner of the checkbox — enter text in the same row to the right of the checkbox
.TopLeftCell.Offset(0, -1) = «Select Country«
‘Value property of a CheckBox indicates whether it is selected or not.
.Value = xlOn
‘.Value = xlOff
‘specify caption text
.Characters.Text = «USA«
‘alternatively:
‘.Caption = «USA«
‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ChkBoxClick macro
.OnAction = «ChkBoxClick«
‘a ShapeRange object represents a subset of shapes on a document — it can contain a single shape, or a few shapes (viz. first, third & fifth shape out of a total of 8 shapes in a sheet), or it could represent all shapes in a document
With .ShapeRange
‘shape will retain its original proportions when it is resized
.LockAspectRatio = msoTrue
‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).
.AlternativeText = «Click to Select«
‘set check box fill / interior
With .Fill
.Visible = msoTrue
.Solid
‘.ForeColor.SchemeColor = 13
.ForeColor.RGB = RGB(255, 255, 0)
.Transparency = 0
End With
‘set border for check box
With .Line
.Weight = 1
.DashStyle = msoLineSolid
.Style = msoLineSingle
.Transparency = 0
.Visible = msoTrue
‘.ForeColor.SchemeColor = 10
.ForeColor.RGB = RGB(255, 0, 0)
End With
End With
End With
‘—————————
‘copy check box and create new check box with same properties
‘set range size, for cell below the existing check box
rng.Offset(1, 0).ColumnWidth = rng.ColumnWidth
rng.Offset(1, 0).RowHeight = rng.Height
‘copy check box to clipboard
ws.Shapes(«Check Box 1»).Copy
‘paste a copy of the checkbox in the same sheet
ws.Paste
‘fit new check box in the cell below the existing check box
Selection.Left = rng.Offset(1, 0).Left
Selection.Top = rng.Offset(1, 0).Top
Selection.Name = «Check Box 2«
Selection.linkedCell = rng.Offset(1, 0).Address
Selection.Caption = «UK«
‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ChkBoxClick macro
Selection.OnAction = «ChkBoxClick«
‘—————————
‘merge & format cells to the left of both check boxes
Union(rng.Offset(0, -1), rng.Offset(1, -1)).Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.ReadingOrder = xlContext
.MergeCells = True
.WrapText = True
.Interior.Color = RGB(0, 255, 0)
.Borders.LineStyle = xlContinuous
.Borders.ColorIndex = 5
.Borders.Weight = xlMedium
End With
End Sub
(2) Use Shapes.AddFormControl Method to create an Excel Form Control (check box) — this returns a Shape object representing the new control — set properties for the Form control (CheckBox) object
Sub FormControl_CheckBox_Shape_Properties_2()
‘use Shapes.AddFormControl Method to create an Excel Form Control (check box) — this returns a Shape object representing the new control — set properties for the Form control (CheckBox) object — Refer Image 3a
Dim shpChBx As Shape, ws As Worksheet, rng As Range, objChBx As OLEObject
Set ws = Sheets(«Sheet1»)
ws.Activate
Set rng = ws.Range(«B2»)
‘delete ActiveX Control CheckBox objects
For Each objChBx In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objChBx.Object) = «CheckBox» Then objChBx.Delete
Next objChBx
‘delete Form Control CheckBox objects
For Each shpChBx In ActiveSheet.Shapes
If shpChBx.Type = msoFormControl Then
If shpChBx.FormControlType = xlCheckBox Then shpChBx.Delete
End If
Next shpChBx
‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property
rng.ColumnWidth = 10
‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.
rng.RowHeight = 15
‘for an already existing Form Control shape — Check Box, with the name «Check Box 1»
‘Set shpChBx = ws.Shapes(«Check Box 1»)
‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):
‘set object variable to the newly added check box Form control — position & size the Check Box with the cell assigned to the rng variable
Set shpChBx = ws.Shapes.AddFormControl(xlCheckBox, Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height)
With shpChBx
‘set a String value as object’s name
.Name = «Check Box 1«
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
‘shape will retain its original proportions when it is resized
.LockAspectRatio = msoTrue
‘specify caption text
‘TextFrame Property returns a TextFrame object which contains the alignment & anchoring properties for a shape — valid for only a shape having a text frame
.TextFrame.Characters.Text = «USA«
‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).
.AlternativeText = «Click to Select«
‘use the .OLEFormat.Object object to manipulate Display3DShading
.OLEFormat.Object.Display3DShading = False
‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ChkBoxClick macro
.OnAction = «ChkBoxClick«
‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.
With .ControlFormat
‘True (for Enabled Property) indicates that the control can be accessed through a vba code & respond to user-generated events (ie. the user can interact with the control by using mouse, keystrokes, accelerators, or hotkeys).
‘enable the object
.Enabled = True
‘check box will be printed when the document is printed
.PrintObject = True
.linkedCell = rng.Address
‘Value property of a CheckBox indicates whether it is selected or not.
.Value = xlOn
‘.Value = xlOff
End With
‘set check box fill / interior
With .Fill
.Visible = msoTrue
.Solid
‘.ForeColor.SchemeColor = 13
.ForeColor.RGB = RGB(255, 255, 0)
.Transparency = 0
End With
‘set border for check box
With .Line
.Weight = 1
.DashStyle = msoLineSolid
.Style = msoLineSingle
.Transparency = 0
.Visible = msoTrue
‘.ForeColor.SchemeColor = 10
.ForeColor.RGB = RGB(255, 0, 0)
End With
End With
‘————————————-
‘copy check box and create new check box with same properties
‘set range size, for cell below the existing check box
rng.Offset(1, 0).ColumnWidth = rng.ColumnWidth
rng.Offset(1, 0).RowHeight = rng.Height
‘copy check box to clipboard
ws.Shapes(«Check Box 1»).Copy
‘paste a copy of the checkbox in the same sheet
ws.Paste
‘fit new check box in the cell below the existing check box
Selection.Left = rng.Offset(1, 0).Left
Selection.Top = rng.Offset(1, 0).Top
Selection.Name = «Check Box 2«
Selection.linkedCell = rng.Offset(1, 0).Address
Selection.Characters.Text = «UK«
‘alternatively
‘Selection.Caption = «UK«
‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ChkBoxClick macro
Selection.OnAction = «ChkBoxClick«
‘enter text in the same row to the left of the checkbox
rng.Offset(0, -1) = «Select Country«
‘merge & format cells to the left of both check boxes
Union(rng.Offset(0, -1), rng.Offset(1, -1)).Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.ReadingOrder = xlContext
.MergeCells = True
.WrapText = True
.Interior.Color = RGB(0, 255, 0)
.Borders.LineStyle = xlContinuous
.Borders.ColorIndex = 5
.Borders.Weight = xlMedium
End With
End Sub
Use with (1) or (2) above: Macro to which the Form Control Check Boxes are assigned — this procedure is located in a standard module of the workbook & executes on clicking the Form Control check boxes («Check Box 1» & «Check Box 2»)
Sub ChkBoxClick()
On Error Resume Next
Dim shpChBx1 As Shape, shpChBx2 As Shape, ws As Worksheet
Set ws = Sheets(«Sheet4»)
ws.Activate
Set shpChBx1 = ws.Shapes(«Check Box 1»)
Set shpChBx2 = ws.Shapes(«Check Box 2»)
If shpChBx1.ControlFormat.Value = xlOn Then
If shpChBx2.ControlFormat.Value = xlOff Then
Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»USA«
Else
Range(«$A$5:$B$13»).AutoFilter Field:=1
End If
Else
If shpChBx2.ControlFormat.Value = xlOff Then
Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»«
Else
Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»UK«
End If
End If
End Sub
Example: ActiveX Control CheckBox(es) & Macro associated with the Click event of the CheckBox:
Add a new OLEObject to a sheet — ActiveX control (CheckBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 3b
Sub ActiveXControl_CheckBox_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (CheckBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 3b
Dim ws As Worksheet, rng As Range
‘OLEObject is not used for Form Controls
Dim objChBx As OLEObject
Set ws = Sheets(«Sheet1»)
ws.Activate
Set rng = ws.Range(«B2»)
‘delete Form Control CheckBox objects in worksheet
ws.CheckBoxes.Delete
‘delete ActiveX Control CheckBox objects
For Each objChBx In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objChBx.Object) = «CheckBox» Then objChBx.Delete
Next objChBx
‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property
rng.ColumnWidth = 10
‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.
rng.RowHeight = 15
‘for an already existing ActiveX control checkbox, with the name «CheckBox1»
‘Set objChBx = ws.OLEObjects(«CheckBox1»)
‘set object variable to the newly added check box ActiveX control — position & size the CheckBox with the cell assigned to the rng variable
Set objChBx = ws.OLEObjects.Add(ClassType:=»Forms.CheckBox.1«, DisplayAsIcon:=False, Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height)
With objChBx
‘set a String value as object’s name
.Name = «CheckBox1«
‘returns the index number of the object within the collection of similar objects
MsgBox .Index
‘set shadow
.Shadow = True
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlMove
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
‘True (for Enabled property) indicates that the control can be accessed through a vba code & respond to user-generated events (ie. the user can interact with the control by using mouse, keystrokes, accelerators, or hotkeys) — enable the object
.Enabled = True
‘this property is ignored by ActiveX controls because these controls always load when a workbook is opened
.AutoLoad = True
‘check box will be printed when the document is printed
.PrintObject = True
‘ControlSource Property specifies a cell to set or store the Value property — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.
‘.LinkedCell = «Sheet1!B2«
.linkedCell = rng.Address
‘wrt to the cell which is under the upper-left corner of the checkbox — enter text in the same row to the right of the checkbox
.TopLeftCell.Offset(0, -1) = «Country«
‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object
‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object
With .Object
.TextAlign = fmTextAlignCenter
‘will enable CheckBox to have three possible values, including the Null value, besides True & False
.TripleState = False
‘Value property of a CheckBox indicates whether it is selected or not. True (integer value 1) indicates that the CheckBox is selected, False (value of 0) indicates that it is cleared; and the Null value indicates that it is neither selected nor cleared, and the CheckBox will appear shaded in this case. The value of TripleState property should be set to True for the CheckBox to have a Null value.
.Value = True
‘determines how the control visually appears
.SpecialEffect = fmButtonEffectFlat
‘specify how caption will appear relative to the control
.Alignment = fmAlignmentLeft
‘Accelerator Property sets the key to access a control
.Accelerator = «h«
‘specify type of mouse pointer
.MousePointer = fmMousePointerArrow
‘load a picture into ActiveX control, using the LoadPicture Function — specify filename & address of image to be loaded
.Picture = LoadPicture(«C:UsersamitDocumentsPhotosDollar.jpg»)
‘alignment of the picture with its caption
.PicturePosition = fmPicturePositionAboveCenter
‘remove picture
.Picture = LoadPicture(«»)
‘specify caption text
.Caption = «USA«
‘caption text will wrap to the next line
.WordWrap = True
‘setting AutoSize to True automatically resizes the Caption while False (Default option) keeps the caption size constant wherein content exceeding the control area gets cut.
.AutoSize = False
‘set the background color for control to yellow
.BackColor = RGB(255, 255, 0)
‘set font color to red
.ForeColor = RGB(255, 0, 0)
‘set background to be Opaque or Transparent — BackStyle property should be set to fmBackStyleOpaque for the BackColor to have any effect
.BackStyle = fmBackStyleOpaque
With .Font
.Name = «Arial«
.Bold = True
.Size = 10
.Italic = False
.Underline = False
End With
End With
‘——————————
‘copy check box and create new check box with same properties
‘set range size, for cell below the existing check box
rng.Offset(1, 0).ColumnWidth = rng.ColumnWidth
rng.Offset(1, 0).RowHeight = rng.Height
‘copy check box to clipboard
.Copy
‘paste a copy of the checkbox in the same sheet
ws.Paste
‘fit new check box in the cell below the existing check box
Selection.Left = rng.Offset(1, 0).Left
Selection.Top = rng.Offset(1, 0).Top
Selection.Name = «CheckBox2«
ws.OLEObjects(«CheckBox2»).linkedCell = rng.Offset(1, 0).Address
ws.OLEObjects(«CheckBox2»).Object.Caption = «UK«
‘——————————
‘merge & format cells to the left of both check boxes
Union(rng.Offset(0, -1), rng.Offset(1, -1)).Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.ReadingOrder = xlContext
.MergeCells = True
.Interior.Color = RGB(0, 255, 0)
End With
End With
End Sub
Macro associated with the Click event of the CheckBox1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (CheckBox1)
Private Sub CheckBox1_Click()
On Error Resume Next
If CheckBox1.Object.Value = True Then
If CheckBox2.Object.Value = False Then
Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»USA«
Else
Range(«$A$5:$B$13»).AutoFilter Field:=1
End If
Else
If CheckBox2.Object.Value = False Then
Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»«
Else
Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»UK«
End If
End If
End Sub
Macro associated with the Click event of the CheckBox2: this Event-handler procedure must be located in the code module of the object worksheet containing the control (CheckBox2)
Private Sub CheckBox2_Click()
On Error Resume Next
If CheckBox2.Object.Value = True Then
If CheckBox1.Object.Value = False Then
Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»UK«
Else
Range(«$A$5:$B$13»).AutoFilter Field:=1
End If
Else
If CheckBox1.Object.Value = False Then
Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»«
Else
Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»USA«
End If
End If
End Sub
List Box & Combo Box — Form Control / ActiveX Control
A List Box or Combo Box is a list of items from which a user can select. They facilitate in accepting data from users and making entries in an Excel worksheet. List box may be of 3 types: (i) a single-selection list box which allows selection of a single item only; (ii) A multiple-selection list box which allows selection of one or more contiguous (adjacent) items; (iii) An extended-selection list box which allows selection of either a single item, or selection of multiple contiguous or noncontiguous items.
Difference between List Box and Combo Box:
1. The Combo Box is a drop-down list (the user-entered item or the list-selected item is visible in the text area, whereas list values are visible by using the drop-down), while a List Box shows a certain number of values with or without a scroll bar. In a Combo Box, only one row of items is visible at a given time (without using the drop-down) whereas in a List Box one or more can be visible at a time.
2. In a Combo Box you can select ony one option from the list, while in a List Box you can select multiple options from the list.
3. The user can enter his own item (in text area) in a ComboBox if it is not included in the list, which is not possible to do in a List Box. In this sense, Combo Box is a combination of Text Box and List Box.
4. Check Box can be used within List Box, but not within Combo Box. List Box allows you to display a check box next to each item in the list, to enable user to select items (this might be easier for the user than using the multiple selection methods).
Below we illustrate: (i) a Form Control List Box & and assign it to a Macro; and (ii) an ActiveX Control ListBox & a Macro associated with the Click event of this ListBox.
Example: Form Control List Box & Macro to which it is assigned:
Create an Excel Form Control (list box) & set ListBox properties — use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Refer Image 4a
Sub FormControl_ListBox_Shape_Properties_1()
‘create an Excel Form Control (list box) & set ListBox properties — use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Refer Image 4a
‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.
‘Forms ListBox allows a single column, use an ActiveX ListBox for multi columns
Dim shpListBx As Shape, ws As Worksheet, rngListBx As Range, rngSource As Range, objListBx As OLEObject, i As Integer
Set ws = Sheets(«Sheet1»)
ws.Activate
‘set range/cell for ListBox
Set rngListBx = ws.Range(«A10»)
‘delete ActiveX Control ListBox objects
For Each objListBx In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objListBx.Object) = «ListBox» Then objListBx.Delete
Next objListBx
‘delete Form Control ListBox objects
For Each shpListBx In ActiveSheet.Shapes
If shpListBx.Type = msoFormControl Then
If shpListBx.FormControlType = xlListBox Then shpListBx.Delete
End If
Next shpListBx
Set rngSource = Range(«A3:A7»)
‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property
rngListBx.ColumnWidth = 11
‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.
rngListBx.RowHeight = 30
‘for an already existing Form Control shape — ListBox, with the name «List Box 1»
‘Set shpListBx = ws.Shapes(«List Box 1»)
‘set object variable to the newly added ListBox Form control — position & size the ListBox with the cell assigned to the rngListBx variable
‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):
Set shpListBx = ws.Shapes.AddFormControl(xlListBox, Left:=rngListBx.Left, Top:=rngListBx.Top, Width:=rngListBx.Width, Height:=rngListBx.Height)
‘to remove all items from listbox (not required for the newly created list box):
With shpListBx
‘remove all items if List Method has been used to set the text entries in the specified list box as an array of strings, or if the AddItem Method has been used to add items to a list box
If .ControlFormat.ListFillRange = «« Then
‘ControlFormat.ListCount Property determines the total number of items in a ListBox or ComboBox.
For i = .ControlFormat.ListCount To 1 Step -1
‘ControlFormat.RemoveItem Method removes one or more items from a list box or combo box — ControlFormat.RemoveItem(Index, Count) — Index is the number of the first item to be removed, having values from 1 to the number of items in the list — this method will fail if the list box has a defined fill range.
.ControlFormat.RemoveItem (i)
Next
Else
‘clear ListBox if filled with ListFillRange/RowSource (if ListFillRange property has been used to specify the source of a list)
.ControlFormat.ListFillRange = ««
End If
‘set a String value as object’s name
.Name = «List Box 1«
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
‘shape will not retain its original proportions when it is resized
.LockAspectRatio = msoFalse
.AlternativeText = «LB«
‘turn 3D Shading Off
.OLEFormat.Object.Display3DShading = False
‘enable the object
.ControlFormat.Enabled = True
‘set ControlFormat.PrintObject Property to True where list box will be printed when the document is printed
.ControlFormat.PrintObject = True
‘ControlFormat.ListFillRange property specifies the source of a list (which could be a worksheet range in Excel), for a ComboBox or ListBox.
.ControlFormat.ListFillRange = rngSource.Address
‘alternatively:
‘.ControlFormat.ListFillRange = «$A$2:$A$7«
‘.ControlFormat.ListFillRange = Range(«A2:A7»).Address
‘.ControlFormat.ListFillRange = «NamedRange«
‘———————
‘ControlFormat.List Method returns or sets the text entries in the specified list box or a combo box, as an array of strings, or returns or sets a single text entry. An error occurs if there are no entries in the list — ControlFormat.List (Index)
‘fill ListBox
‘.OLEFormat.Object.List = rngSource.Value
‘.OLEFormat.Object.List = Range(«A2:A7»).Value
‘replace value of the second item in the list, after folling listbox using the ControlFormat.List Method:
‘.OLEFormat.Object.List(2) = «ChangeItem«
‘.OLEFormat.Object.List = Array(«2010», «2011», «2012», «2013»)
‘return first item:
MsgBox .ControlFormat.List(1)
‘alternatively — return first item:
MsgBox .OLEFormat.Object.List(1)
‘———————
‘ControlFormat.MultiSelect Property: Specifies whether multiple selections are allowed. There are 3 settings: (i) xlNone, the default setting, wherein only a single item can be selected; (ii) xlSimple which allows multiple selections wherein an item can be selected or deselected by clicking mouse or pressing SPACEBAR; and (iii) xlExtended which allows multiple selections, wherein by pressing SHIFT and simultaneously moving the up or down arrows (or pressing SHIFT and clicking mouse) continues selection from the previously selected item to the current selection (ie. a continuous selection) & this option also allows to select or deselect an item by pressing CTRL and clicking mouse.
.ControlFormat.MultiSelect = xlNone
‘ControlFormat.ListIndex Property returns or sets the index number of the currently selected item in a ComboBox or ListBox. This property cannot be used with multiselect list boxes.
.ControlFormat.ListIndex = 3
‘return selected item from ListBox ie. the value of list box — cannot be used with a multi-select ListBox
MsgBox .ControlFormat.List(.ControlFormat.ListIndex)
‘or:
‘return selected item(s) from ListBox — this can be used with a multi-select ListBox
‘ControlFormat.ListCount Property returns the total number of entries in a ListBox or ComboBox, & returns 0 (zero) for no entries in the list
For i = 1 To .ControlFormat.ListCount
‘Selected Property specifies whether an item is selected in a ListBox control (not valid for ComboBox). Syntax: Control.Selected(Item_Index).
If .OLEFormat.Object.Selected(i) Then
MsgBox .ControlFormat.List(i)
End If
Next i
‘Value Property: For the Form Controls ComboBox & ListBox (value cannot be used with a multi-select ListBox), value is the the index number of the currently selected item (ie. ControlFormat.ListIndex)
MsgBox .ControlFormat.Value
‘use the ControlFormat.LinkedCell property (not valid for a multi-select ListBox), to set the worksheet range linked to the index number of the currently selected item in a ComboBox or ListBox (ie. ControlFormat.ListIndex)
‘enter the selection’s list position to a specific cell
.ControlFormat.linkedCell = rngListBx.Address
‘to return the actual item from the input range, enter the index formula in the separate cell wherein you wish to get the actual item
rngListBx.Offset(-1, 0).Value = Application.WorksheetFunction.Index(rngSource, rngListBx.Value)
‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ListBox_Change macro
.OnAction = «ListBox_Change»
End With
‘call the assigned macro
Call ListBox_Change
End Sub
Macro to which the Form Control ListBox is assigned — this procedure is located in a standard module of the workbook & executes on clicking / changing «List Box 1» value
Sub ListBox_Change()
‘this macro has been assigned to the «List Box 1» & will execute when the listbox value changes
Dim shpListBx As Shape, ws As Worksheet
Set ws = Sheets(«Sheet1»)
ws.Activate
‘set object variable to an existing Form Control shape — ListBox
Set shpListBx = ws.Shapes(«List Box 1»)
‘call the Sales_Region sub — argument / value is being supplied by this code to the Sales_Region procedure when it is called
‘when arguments are passed to a procedure from other procedures, then these are listed or declared between the parentheses viz. shpListBx.ControlFormat.Value
Call Sales_Region(shpListBx.ControlFormat.Value)
End Sub
This procedure is located in a standard module of the workbook & is called by the above macro (to which the Form Control ListBox is assigned)
Sub Sales_Region(i As Integer)
‘an external argument (Integer value) supplied by the calling sub (ListBox_Change) is used by this procedure to perform an action
If i = 1 Then
Call Sales_Total(«I»)
ElseIf i = 2 Then
Call Sales_Total(«G»)
ElseIf i = 3 Then
Call Sales_Total(«H»)
ElseIf i = 4 Then
Call Sales_Total(«E»)
ElseIf i = 5 Then
Call Sales_Total(«F»)
End If
End Sub
This procedure is located in a standard module of the workbook & is called by the above macro
Sub Sales_Total(letter As String)
‘an external argument (String value) supplied by the calling sub (Sales_Region) is used by this procedure to perform an action
Dim shpListBx As Shape, ws As Worksheet, rng As Range, str As String
Set ws = Sheets(«Sheet1»)
Set shpListBx = ws.Shapes(«List Box 1»)
‘linked cell of listbox as a string value
str = shpListBx.ControlFormat.linkedCell
‘set range of linked cell
Set rng = ws.Range(str)
rng.Offset(2, 0).Value = ws.Range(«$» & letter & «$7»).Value
rng.Offset(2, 0).Interior.Color = RGB(0, 255, 0)
End Sub
Example: Create an Excel Form Control (list box) & set ListBox properties — use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control
Sub FormControl_ListBox_Shape_Properties_2()
‘create an Excel Form Control (list box) & set ListBox properties — use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control
‘Forms ListBox allows a single column, use an ActiveX ListBox for multi columns
Dim shpListBx As Shape, ws As Worksheet, rngListBx As Range, rngSource As Range, i As Integer
Set ws = Sheets(«Sheet1»)
ws.Activate
‘set range/cell for ListBox
Set rngListBx = ws.Range(«A10»)
‘delete all Form Control ListBox objects in worksheet:
ws.ListBoxes.Delete
Set rngSource = Range(«A3:A7»)
rngListBx.ColumnWidth = 11
rngListBx.RowHeight = 30
‘set object variable to the newly added ListBox Form control — position & size the ListBox with the cell assigned to the rngListBx variable
‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control
Set shpListBx = ws.Shapes.AddFormControl(xlListBox, Left:=rngListBx.Left, Top:=rngListBx.Top, Width:=rngListBx.Width, Height:=rngListBx.Height)
‘remove all items from listbox (not required for the newly created list box):
With shpListBx
‘remove all items if List Method has been used to set the text entries in the specified list box as an array of strings, or if the AddItem Method has been used to add items to a list box
If .ControlFormat.ListFillRange = «« Then
‘ControlFormat.RemoveAllItems Method removes all entries from a Microsoft Excel list box or combo box.
.ControlFormat.RemoveAllItems
Else
‘clear ListBox if filled with ListFillRange/RowSource (if ListFillRange property has been used to specify the source of a list)
.ControlFormat.ListFillRange = ««
End If
‘set a String value as object’s name
.Name = «List Box 1«
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
‘shape will not retain its original proportions when it is resized
.LockAspectRatio = msoFalse
.AlternativeText = «LB«
‘turn 3D Shading Off
.OLEFormat.Object.Display3DShading = False
‘enable the object
.ControlFormat.Enabled = True
‘set ControlFormat.PrintObject Property to True where list box will be printed when the document is printed
.ControlFormat.PrintObject = True
‘ControlFormat.AddItem Method adds an item to a list box or a combo box — ControlFormat.AddItem(Text, Index) — using this method clears any range specified by the ListFillRange property.
For i = 1 To rngSource.Rows.Count
‘Create a new row with AddItem
.ControlFormat.AddItem rngSource(i, 1).Value
Next i
‘alternatively:
‘With .ControlFormat
‘.AddItem «2010»
‘.AddItem «2011»
‘.AddItem «2012»
‘.AddItem «2013»
‘End With
‘xlSimple allows multiple selections
.ControlFormat.MultiSelect = xlSimple
‘Select multiple items in the ListBox
For i = 1 To .ControlFormat.ListCount
‘select every even item
If i Mod 2 = 0 Then
‘Selected Property specifies whether an item is selected in a ListBox control (not valid for ComboBox). Syntax: Control.Selected(Item_Index).
.OLEFormat.Object.Selected(i) = True
End If
Next i
End With
End Sub
Example: Create an Excel Form Control (list box) — add a new listbox using ListBoxes.Add method
Sub FormControl_ListBox_Properties_3()
‘create an Excel Form Control (list box) — add a new listbox using ListBoxes.Add method
‘Forms ListBox allows a single column, use an ActiveX ListBox for multi columns
Dim ws As Worksheet, rngListBx As Range, rngSource As Range, i As Integer
Set ws = Sheets(«Sheet1»)
ws.Activate
‘set range/cell for ListBox
Set rngListBx = ws.Range(«A10»)
‘delete all Form Control ListBox objects in worksheet:
ws.ListBoxes.Delete
Set rngSource = Range(«A3:A7»)
rngListBx.ColumnWidth = 11
rngListBx.RowHeight = 30
‘position & size the ListBox with the cell assigned to the rngListBx variable
‘add a new listbox — ListBoxes.Add:
ws.ListBoxes.Add(Left:=rngListBx.Left, Top:=rngListBx.Top, Width:=rngListBx.Width, Height:=rngListBx.Height).Select
With Selection
‘alternatively:
‘With ws.ListBoxes.Add(Left:=rngListBx.Left, Top:=rngListBx.Top, Width:=rngListBx.Width, Height:=rngListBx.Height)
‘remove all items if List Method has been used to set the text entries in the specified list box as an array of strings, or if the AddItem Method has been used to add items to a list box or a combo box (not required for the newly created list box)
If .ListFillRange = «« Then
‘RemoveAllItems Method removes all entries from a Microsoft Excel list box or combo box.
.RemoveAllItems
Else
‘clear ListBox if filled with ListFillRange/RowSource (if ListFillRange property has been used to specify the source of a list)
.ListFillRange = ««
End If
‘set a String value as object’s name
.Name = «List Box 1«
.Placement = xlFreeFloating
‘use the Locked Property to lock — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
‘turn 3D Shading Off
.Display3DShading = False
‘enable the object
.Enabled = True
‘set PrintObject Property to True where list box will be printed when the document is printed
.PrintObject = True
‘List Method returns or sets the text entries in the specified list box or a combo box, as an array of strings, or returns or sets a single text entry. An error occurs if there are no entries in the list — ControlFormat.List (Index)
‘fill ListBox
‘.List = rngSource.Value
‘AddItem Method adds an item to a list box or a combo box — AddItem(Text, Index) — using this method clears any range specified by the ListFillRange property.
For i = 1 To rngSource.Rows.Count
‘Create a new row with AddItem
.AddItem rngSource(i, 1).Value
Next i
‘alternatively, add item individually, ie. one by one:
‘.AddItem «2010»
‘.AddItem «2011»
‘.AddItem «2012»
‘.AddItem «2013»
‘xlSimple allows multiple selections
.MultiSelect = xlSimple
‘Select multiple items in the ListBox
For i = 1 To .ListCount
‘select every even item
If i Mod 2 = 0 Then
‘Selected Property specifies whether an item is selected in a ListBox control (not valid for ComboBox). Syntax: Control.Selected(Item_Index).
.Selected(i) = True
End If
Next i
End With
End Sub
Example: ActiveX Control ListBox & Macro associated with the Click event of the ListBox:
Add a new OLEObject to a sheet — ActiveX control (ListBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 4b
Sub ActiveXControl_ListBox_OLEobject_Properties_1()
‘add a new OLEObject to a sheet — ActiveX control (ListBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 4b
Dim ws As Worksheet, rngListBox As Range, rngSource As Range
‘OLEObject is not used for Form Controls
Dim objLB As OLEObject, i As Integer
Set ws = Sheets(«Sheet1»)
ws.Activate
‘set range/cell for ListBox
Set rngListBox = Range(«A8»)
‘delete ActiveX Control ListBox objects
For Each objLB In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objLB.Object) = «ListBox» Then objLB.Delete
Next objLB
‘delete all Form Control ListBox objects in worksheet:
ws.ListBoxes.Delete
Set rngSource = Range(«A2:D7»)
‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range
rngSource.ColumnWidth = 6
‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.
rngListBox.RowHeight = 50
‘ListBox range / cell (rngListBox) resized to add 2 columns
rngListBox.Resize(rngListBox.Rows.Count, rngListBox.Columns.Count + 2).MergeCells = True
‘for an already existing ActiveX control listbox, with the name «ListBox1»
‘Set objLB = ws.OLEObjects(«ListBox1»)
‘set object variable to the newly added listbox ActiveX control
Set objLB = ws.OLEObjects.Add(ClassType:=»Forms.ListBox.1«, DisplayAsIcon:=False, Left:=rngListBox.Left, Top:=rngListBox.Top, Width:=20, Height:=20)
With objLB
‘not required for a new listbox
If .ListFillRange = «« Then
‘Clear Method removes all items in a ComboBox or ListBox — it will not work if ComboBox or ListBox is bound to data, hence RowSource data should be cleared before use.
‘.Object.Clear
‘RemoveItem Method removes a specified row is removed from the list in a ComboBox or ListBox. Syntax: Control.RemoveItem(Row_Index). Row_Index specifies the row number to be removed, wherein the first row is numbered 0.
‘ListCount Property determines the total number of rows in a ListBox or ComboBox.
For i = .Object.ListCount — 1 To 0 Step -1
.Object.RemoveItem (i)
Next
Else
‘clear ListBox if filled with ListFillRange/RowSource
.ListFillRange = ««
End If
‘set a String value as name for the List Box
.Name = «ListBox1«
‘ListFillRange property specifies the source of a list (which could be a worksheet range in Excel), for a ComboBox or ListBox.
.ListFillRange = rngSource.Address
‘alternatively:
‘.ListFillRange = «$A$2:$D$7«
‘.ListFillRange = Range(«A2:D7»).Address
‘.ListFillRange = «NamedRange«
‘LinkedCell property sets the worksheet range linked to the control’s value so that the linked cell displays the selected value from the ListBox control — you cannot link a worksheet cell for MultiSelect ListBox by using the LinkedCell property
‘LinkedCell is to the right of the ListBox cell
With rngListBox.Offset(0, 1)
.Value = ««
.Interior.Color = vbYellow
.HorizontalAlignment = xlCenter
End With
.linkedCell = rngListBox.Offset(0, 1).Address
‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object
With .Object
‘determines how the control visually appears
‘.SpecialEffect = fmSpecialEffectRaised
‘ColumnHeads Property: A Boolean value (True/False) which determines display of column headings (in a single row) for ComboBox or ListBox.
.ColumnHeads = True
‘ColumnCount Property specifies the number of columns to be displayed in a ComboBox or ListBox. A ColumnCount value of 0 does not display any column and a setting of -1 displays all columns.
.ColumnCount = 4
‘set width of each column — displays only the first column
.ColumnWidths = «70;0;0;0«
.BorderStyle = fmBorderStyleSingle
.BorderColor = RGB(255, 0, 0)
.MatchEntry = fmMatchEntryFirstLetter
.ListStyle = fmListStyleOption
‘set background color
.BackColor = RGB(216, 216, 216)
‘set font color to red
.ForeColor = RGB(0, 0, 255)
With .Font
.Name = «Arial«
.Bold = False
.Size = 9
.Italic = False
.Underline = False
End With
‘MultiSelect Property: Specifies whether multiple selections are allowed. There are 3 settings: (i) fmMultiSelectSingle (value 0), the default setting, wherein only a single item can be selected; (ii) fmMultiSelectMulti (value 1) which allows multiple selections wherein an item can be selected or deselected by clicking mouse or pressing SPACEBAR; and (iii) fmMultiSelectExtended (value 2) which allows multiple selections, wherein by pressing SHIFT and simultaneously moving the up or down arrows (or pressing SHIFT and clicking mouse) continues selection from the previously selected item to the current selection (ie. a continuous selection) & this option also allows to select or deselect an item by pressing CTRL and clicking mouse.
.MultiSelect = fmMultiSelectSingle
‘ListIndex Property determines which item is selected in a ComboBox or ListBox. The first item in a list has a ListIndex value of 0, the second item has a value of 1, and so on.
.ListIndex = 1
‘ListCount Property determines the total number of rows in a ListBox or ComboBox.
‘MsgBox .ListCount
‘TextColumn property enables display of one set of values to the user but store a different set of values (per column specified in the BoundColumn property).
‘TextColumn property specifies the column of data in a ListBox that supplies data for its Text property — the TextColumn property determines the column whose value the Text property will return whereas the BoundColumn property determines the column whose value the Value property returns. The Text property returns the same as Value if the TextColumn property is not set. Setting the TextColumn value to -1 indicates that the first column with a ColumnWidths value greater than 0 will be displayed. Setting the TextColumn value to 0 returns the ListIndex value (the number of the selected row) in Text Property — this setting is useful if you want to determine the row of the selected item.
.TextColumn = 1
‘BoundColumn Property: Specifies the column from which value is to be stored in a multicolumn ComboBox or ListBox, when a row is selected by the user. First column has a BoundColumn value of 1
‘Setting the BoundColumn value to 0 assigns the value of the ListIndex property (which is the number of the selected row) as the value of the control (ComboBox or ListBox).
.BoundColumn = 4
‘Value Property: For the controls ComboBox and ListBox (value cannot be used with a multi-select ListBox), it is the value in the BoundColumn of the currently selected row (BoundColumn property specifies the column from which value is to be stored in a multicolumn ComboBox or ListBox, when a row is selected by the user).
MsgBox .Value
End With
‘size the ListBox with the resized range
‘the Range.Width property returns the width of a column in points
.Width = rngListBox.Resize(rngListBox.Rows.Count, rngListBox.Columns.Count + 2).Width
.Height = rngListBox.Height
‘set shadow
.Shadow = False
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
‘enable the object
.Enabled = True
‘list box will be printed when the document is printed
.PrintObject = True
.Activate
End With
End Sub
Macro associated with the Click event of the ListBox1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (ListBox1)
Private Sub ListBox1_Click()
‘on clicking / selecting an item in the ActiveX Control ListBox1
On Error Resume Next
Dim cat As String, str As String, rng As Range, BMI As Single
Set rng = Range(«A10»)
rng.Resize(rng.Rows.Count, rng.Columns.Count + 2).MergeCells = True
‘Body Mass Index formula is — weight in kilograms divided by the square of height in meters: kg/m2
‘BMI Categories:
‘Underweight = <18.5
‘Normal weight = 18.5–24.9
‘Overweight = 25–29.9
‘Obesity = BMI of 30 or greater
‘assign Value property to BMI
BMI = ListBox1.Object.Value
If BMI < 18.5 Then
cat = «Underweight«
ElseIf BMI < 25 Then
cat = «Normal Weight«
ElseIf BMI < 30 Then
cat = «Overweight«
ElseIf BMI >= 30 Then
cat = «Obese«
End If
With rng
.Interior.Color = vbGreen
.HorizontalAlignment = xlCenter
‘Listbox Text Property gives the Name, & BMI Category (cat) is derived from BMI (Listbox Value Property)
.Value = ListBox1.Object.Text & » is » & cat
End With
End Sub
Example: Add a new OLEObject to a sheet — ActiveX control (ListBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 4c
Sub ActiveXControl_ListBox_OLEobject_Properties_2()
‘add a new OLEObject to a sheet — ActiveX control (ListBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 4c
Dim ws As Worksheet, rngListBox As Range, rngSource As Range
‘OLEObject is not used for Form Controls
Dim objLB As OLEObject, i As Integer
Set ws = Sheets(«Sheet9»)
ws.Activate
‘set range/cell for ListBox
Set rngListBox = Range(«A8»)
‘delete ActiveX Control ListBox objects
For Each objLB In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objLB.Object) = «ListBox» Then objLB.Delete
Next objLB
‘delete Form Control ListBox objects
Dim sh As Shape
For Each sh In ActiveSheet.Shapes
If sh.Type = msoFormControl Then
If sh.FormControlType = xlListBox Then sh.Delete
End If
Next sh
Set rngSource = Range(«A2:C7»)
‘ListBox range / cell (rngListBox) resized to add 2 columns
rngListBox.Resize(rngListBox.Rows.Count, rngListBox.Columns.Count + 2).MergeCells = True
‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range
rngListBox.Resize(1, rngListBox.Columns.Count + 2).ColumnWidth = 9
‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.
rngListBox.RowHeight = 40
‘for an already existing ActiveX control listbox, with the name «ListBox1»
‘Set objLB = ws.OLEObjects(«ListBox1»)
‘set object variable to the newly added listbox ActiveX control
Set objLB = ws.OLEObjects.Add(ClassType:=»Forms.ListBox.1«, DisplayAsIcon:=False, Left:=rngListBox.Left, Top:=rngListBox.Top, Width:=100, Height:=20)
With objLB
‘not required for a new listbox
If .ListFillRange = «» Then
‘.Object.Clear
‘deleting row from ListBox using RemoveItem method:
For i = .Object.ListCount — 1 To 0 Step -1
.Object.RemoveItem (i)
Next
Else
‘clear ListBox if filled with ListFillRange/RowSource
.ListFillRange = ««
End If
‘set a String value as name for the List Box
.Name = «ListBox1«
‘remove LinkedCell — you cannot link a worksheet cell for MultiSelect ListBox by using the LinkedCell property
.linkedCell = ««
‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object
With .Object
‘do not display column headings
.ColumnHeads = False
‘ColumnCount Property specifies the number of columns to be displayed in a ComboBox or ListBox. A ColumnCount value of 0 does not display any column and a setting of -1 displays all columns.
.ColumnCount = 3
‘set width of each column
.ColumnWidths = «50;40;40«
‘allow multiple selections in ListBox
.MultiSelect = fmMultiSelectMulti
.BorderStyle = fmBorderStyleSingle
.BorderColor = RGB(255, 0, 0)
.MatchEntry = fmMatchEntryFirstLetter
.ListStyle = fmListStyleOption
‘set background color
.BackColor = RGB(216, 216, 216)
‘set font color to red
.ForeColor = RGB(0, 0, 255)
With .Font
.Name = «Arial«
.Bold = False
.Size = 9
.Italic = False
.Underline = False
End With
‘AddItem Method adds an item to the list (in a single-column ListBox or ComboBox) & adds a row to the list or an item for each row (in a multi-column ListBox or ComboBox). Syntax: Control.AddItem(Item, Index). Item specifies the item or row to add. Index specifies the position where the new item or row is placed within the list, and if omitted, the item or row is added at the end. The item or row numbers begin with zero, and the first item or row is numbered 0, and so on. The value of Index cannot be greater than the total number of rows (ie. value of ListCount property). AddItem method will not work if ComboBox or ListBox is bound to data, hence RowSource data should be cleared before use.
Dim iRow As Integer, iColumn As Integer
For iRow = 1 To rngSource.Rows.Count
‘Create a new row with AddItem
.AddItem rngSource(iRow, 1).Value
For iColumn = 2 To rngSource.Columns.Count
‘add item in columns of each row, using List property
.List(iRow — 1, iColumn — 1) = rngSource(iRow, iColumn).Value
Next iColumn
Next iRow
‘In a Multiple Selection enabled ListBox, ListIndex returns the index of the row that has focus, irrespective of whether that row is selected or not. Hence the Selected property of the ListBox (and not the ListIndex property) shoud be used here to return and set a selection.
‘Select items in the ListBox
For i = 1 To .ListCount
‘select every even item
If i Mod 2 = 0 Then
‘Selected Property specifies whether an item is selected in a ListBox control (not valid for ComboBox). Syntax: Control.Selected(Item_Index).
.Selected(i — 1) = True
End If
Next i
‘copying Selected rows in a multi-column ListBox to corresponding worksheet rows & columns, below the ListBox:
Dim counter As Integer
counter = 0
For i = 0 To .ListCount — 1
If .Selected(i) = True Then
counter = counter + 1
For iColCount = 1 To .ColumnCount
ws.Cells(rngListBox.Row + counter, iColCount).Value = .List(i, iColCount — 1)
‘alternatively, use Column Property instead of List property
‘Column Property refers to a specific column, or column and row combination, in a multiple-column ComboBox or ListBox. Syntax: Control.Column(iColumn, iRow).iColumn specifies the column number & iRow specifies the row number wherein both column & row nos start with zero for the first column & row. Specifying both column and row numbers will refer to a specific item, and specifying only the column number will refer to a specific column in the current row viz. ListBox1.Column(1) refers the second column.
‘ws.Cells(rngListBox.Row + counter, iColCount).Value = .Column(iColCount — 1, i)
Next iColCount
End If
Next i
End With
‘size the ListBox with the resized range
‘the Range.Width property returns the width of a column in points
.Width = rngListBox.Resize(rngListBox.Rows.Count, rngListBox.Columns.Count + 2).Width
‘Range.Height Property returns or sets the height of the range, in points
.Height = rngListBox.Height
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
‘enable the object
.Enabled = True
.Activate
End With
End Sub
Example: Form Control Combo Box & Macro to which it is assigned:
Create an Excel Form Control (combo box) & set ComboBox properties — use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Refer Image 5a
Sub FormControl_ComboBox_Shape_Properties()
‘create an Excel Form Control (combo box) — use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — refer Image 5a
‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.
‘Form Control ComboBox allows a single column, use an ActiveX ComboBox for multi columns
‘use an ActiveX ComboBox to enable the user to edit the text in the text box — Form Control ComboBox does not allow this
Dim shpComboBx As Shape, ws As Worksheet, rngComboBx As Range, rngSource As Range, objComboBx As OLEObject, i As Integer
Set ws = Sheets(«Sheet1»)
ws.Activate
‘set range/cell for ComboBox
Set rngComboBx = ws.Range(«B10»)
‘delete ActiveX Control ComboBox objects
For Each objComboBx In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objComboBx.Object) = «ComboBox» Then objComboBx.Delete
Next objComboBx
‘delete Form Control ComboBox objects
For Each shpComboBx In ActiveSheet.Shapes
If shpComboBx.Type = msoFormControl Then
If shpComboBx.FormControlType = xlDropDown Then shpComboBx.Delete
End If
Next shpComboBx
Set rngSource = Range(«B2:F2»)
‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property
rngComboBx.ColumnWidth = 11
‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.
rngComboBx.RowHeight = 17
‘for an already existing Form Control shape — ComboBox, with the name «Combo Box 1»
‘Set shpComboBx = ws.Shapes(«Combo Box 1»)
‘set object variable to the newly added ComboBox Form control — position & size the ComboBox with the cell assigned to the rngComboBx variable
‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):
Set shpComboBx = ws.Shapes.AddFormControl(xlDropDown, Left:=rngComboBx.Left, Top:=rngComboBx.Top, Width:=rngComboBx.Width, Height:=rngComboBx.Height)
‘remove all items from ComboBox:
With shpComboBx
‘remove all items if List Method has been used to set the text entries in the specified list box as an array of strings, or if the AddItem Method has been used to add items to a list box
If .ControlFormat.ListFillRange = «« Then
‘ControlFormat.RemoveAllItems Method removes all entries from a Microsoft Excel list box or combo box.
‘.ControlFormat.RemoveAllItems
‘ControlFormat.ListCount Property determines the total number of items in a ListBox or ComboBox.
For i = .ControlFormat.ListCount To 1 Step -1
‘ControlFormat.RemoveItem Method removes one or more items from a list box or combo box — ControlFormat.RemoveItem(Index, Count) — Index is the number of the first item to be removed, having values from 1 to the number of items in the list — this method will fail if the list box has a defined fill range.
.ControlFormat.RemoveItem (i)
Next
Else
‘clear ComboBox if filled with ListFillRange/RowSource (if ListFillRange property has been used to specify the source of a list)
.ControlFormat.ListFillRange = ««
End If
‘set a String value as object’s name
.Name = «Combo Box 1«
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
‘shape will retain its original proportions when it is resized
.LockAspectRatio = msoTrue
.AlternativeText = «ComBx«
‘turn 3D Shading Off
.OLEFormat.Object.Display3DShading = True
‘enable the object
.ControlFormat.Enabled = True
‘set ControlFormat.PrintObject Property to True where list box will be printed when the document is printed
.ControlFormat.PrintObject = True
‘ControlFormat.ListFillRange property specifies the source of a list (which could be a worksheet range in Excel), for a ComboBox or ListBox.
.ControlFormat.ListFillRange = rngSource.Address
‘alternatively:
‘.ControlFormat.ListFillRange = «$B$2:$F$2»
‘.ControlFormat.ListFillRange = Range(«B2:F2»).Address
‘.ControlFormat.ListFillRange = «NamedRange»
‘———————
‘ControlFormat.List Method returns or sets the text entries in the specified list box or a combo box, as an array of strings, or returns or sets a single text entry. An error occurs if there are no entries in the list — ControlFormat.List(Index)
‘fill ComboBox
‘.OLEFormat.Object.List = rngSource.Value
‘.OLEFormat.Object.List = Range(«B2:F2»).Value
‘replace value of the second item in the list, using the ControlFormat.List Method:
‘.OLEFormat.Object.List(2) = «ChangeItem»
‘.OLEFormat.Object.List = Array(«2010», «2011», «2012», «2013»)
‘return first item:
MsgBox .ControlFormat.List(1)
‘alternatively — return first item:
MsgBox .OLEFormat.Object.List(1)
‘ControlFormat.DropDownLines Property returns or sets the number of list lines displayed in the drop-down portion of a combo box. ControlFormat.DropDownLines
.ControlFormat.DropDownLines = 3
‘ControlFormat.AddItem Method adds an item to a list box or a combo box — ControlFormat.AddItem(Text, Index) — using this method clears any range specified by the ListFillRange property.
For i = 1 To rngSource.Columns.Count
‘Create a new row with AddItem
.ControlFormat.AddItem rngSource(1, i).Value
Next i
‘alternatively:
‘With .ControlFormat
‘.AddItem «2010»
‘.AddItem «2011»
‘.AddItem «2012»
‘.AddItem «2013»
‘End With
‘ControlFormat.ListIndex Property returns or sets the index number of the currently selected item in a ComboBox or ListBox. This property cannot be used with multiselect list boxes.
‘ComboBox displays the current value in the text box, regardless of how that value is entered
.ControlFormat.ListIndex = 1
‘return selected item from ComboBox
MsgBox .ControlFormat.List(.ControlFormat.ListIndex)
‘ControlFormat.ListCount Property returns the total number of entries in a ListBox or ComboBox, & returns 0 (zero) for no entries in the list
MsgBox .ControlFormat.ListCount
‘Value Property: For the Form Controls ComboBox & ListBox (value cannot be used with a multi-select ListBox), value is the the index number of the currently selected item (ie. ControlFormat.ListIndex)
MsgBox .ControlFormat.Value
‘use the ControlFormat.LinkedCell property (not valid for a multi-select ComboBox), to set the worksheet range linked to the index number of the currently selected item in a ComboBox or ListBox (ie. ControlFormat.ListIndex)
‘enter the selection’s list position to a specific cell — the linked cell returns the number of the selected item in the drop-down list of the combo box.
.ControlFormat.linkedCell = rngComboBx.Address
‘to return the actual item from the input range, enter the index formula in the separate cell wherein you wish to get the actual item
‘rngComboBx.Offset(-1, 0).Value = Application.WorksheetFunction.Index(rngSource, rngComboBx.Value)
‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ComboBoxClick macro
.OnAction = «ComboBoxClick«
End With
‘————————————-
‘copy combo box and create new combo box with same properties
‘set range size, for cell below the existing combo box
rngComboBx.Offset(1, 0).ColumnWidth = rngComboBx.ColumnWidth
rngComboBx.Offset(1, 0).RowHeight = rngComboBx.Height
‘copy combo box to clipboard
ws.Shapes(«Combo Box 1»).Copy
‘paste a copy of the combobox in the same sheet
ws.Paste
‘fit new combo box in the cell below the existing check box
Selection.Left = rngComboBx.Offset(1, 0).Left
Selection.Top = rngComboBx.Offset(1, 0).Top
Selection.Name = «Combo Box 2«
Selection.linkedCell = rngComboBx.Offset(1, 0).Address
‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ComboBoxClick macro
Selection.OnAction = «ComboBoxClick«
Dim rngSource2 As Range
Set rngSource2 = Range(«A3:A7»)
ws.Shapes(«Combo Box 2»).OLEFormat.Object.List = rngSource2.Value
‘————————————-
‘call the ComboBoxClick macro
Call ComboBoxClick
End Sub
Macro to which the Form Control ComboBox is assigned — this procedure is located in a standard module of the workbook & executes on clicking / changing «Combo Box 1» or «Combo Box 2» value
Sub ComboBoxClick()
‘this macro has been assigned to «Combo Box 1» & «Combo Box 2», & will execute when combobox selection changes
Dim shpComboBx1 As Shape, shpComboBx2 As Shape, ws As Worksheet, rngSource As Range, rngResult As Range, c As Integer, r As Integer
Set ws = Sheets(«Sheet1»)
ws.Activate
Set rngSource = Range(«B3:F7»)
Set rngResult = Range(«B13»)
‘set object variable to an existing Form Control shape — ComboBox
Set shpComboBx1 = ws.Shapes(«Combo Box 1»)
Set shpComboBx2 = ws.Shapes(«Combo Box 2»)
‘column number in range given by combo box 1
c = shpComboBx1.ControlFormat.Value
‘row number in range given by combo box 2
r = shpComboBx2.ControlFormat.Value
rngResult.Value = Application.WorksheetFunction.Index(rngSource, r, c)
rngResult.Interior.Color = RGB(0, 255, 0)
rngResult.NumberFormat = «$#,##0«
End Sub
Example: ActiveX Control ComboBox & Macro associated with the Click event of the ComboBox:
Add a new OLEObject to a sheet — ActiveX control (ComboBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 5b
Sub ActiveXControl_ComboBox_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (ComboBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 5b
Dim ws As Worksheet, rngComboBox As Range, rngSource As Range
‘OLEObject is not used for Form Controls
Dim objCoBx As OLEObject, i As Integer
Set ws = Sheets(«Sheet1»)
ws.Activate
‘set range/cell for ComboBox
Set rngComboBox = Range(«A8»)
‘delete ActiveX Control ComboBox objects
For Each objCoBx In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objCoBx.Object) = «ComboBox» Then objCoBx.Delete
Next objCoBx
‘delete all Form Control ComboBox objects in worksheet:
ws.DropDowns.Delete
Set rngSource = Range(«A2:D7»)
‘ListBox range / cell (rngComboBox) resized to add 2 columns
rngComboBox.Resize(rngComboBox.Rows.Count, rngComboBox.Columns.Count + 3).MergeCells = True
‘Range.ColumnWidth Property sets the width of all columns in the specified range
rngComboBox.Resize(1, rngComboBox.Columns.Count + 3).ColumnWidth = 7
‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.
rngComboBox.RowHeight = 18
‘for an already existing ActiveX control ComboBox, with the name «ComboBox1»
‘Set objCoBx = ws.OLEObjects(«ComboBox1»)
‘set object variable to the newly added listbox ActiveX control
Set objCoBx = ws.OLEObjects.Add(ClassType:=»Forms.ComboBox.1«, DisplayAsIcon:=False, Left:=rngComboBox.Left, Top:=rngComboBox.Top, Width:=40, Height:=20)
With objCoBx
‘set a String value as name for the List Box
.Name = «ComboBox1«
‘LinkedCell property sets the worksheet range linked to the control’s value so that the linked cell displays the selected value from the ComboBox control
‘LinkedCell is 1 column to the right of the ComboBox cell
With rngComboBox.Offset(0, 1)
.NumberFormat = «#,##0.0«
.Value = ««
.Interior.Color = vbYellow
.HorizontalAlignment = xlCenter
End With
.linkedCell = rngComboBox.Offset(0, 1).Address
‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object
With .Object
‘display column headings (if combobox is filled with ListFillRange/RowSource)
.ColumnHeads = True
‘ColumnCount Property specifies the number of columns to be displayed in a ComboBox or ListBox. A ColumnCount value of 0 does not display any column and a setting of -1 displays all columns.
.ColumnCount = 3
‘set width of each column
.ColumnWidths = «50;40;40«
‘fmShowDropButtonWhenAlways — always shows the drop-down button; fmShowDropButtonWhenNever — never shows the drop-down button; fmShowDropButtonWhenFocus — shows the drop-down button only when the control has focus.
.ShowDropButtonWhen = fmShowDropButtonWhenAlways
‘Style Property determines choosing or setting the value of ComboBox (not valid for ListBox). There are 2 settings: (i) fmStyleDropDownCombo (value 0 — default) — user has both options of typing a custom value in the text area or select from the drop-down list; (ii) fmStyleDropDownList (value 2) — user can only select from the drop-down list, like in ListBox.
.Style = fmStyleDropDownCombo
‘enabling the DragBehavior property enables the drag-and-drop feature for ComboBox — dragging in combo box starts a drag-and-drop operation on the selected text but not in the drop-down portion — DragBehavior has no effect on a ComboBox whose Style property is set to fmStyleDropDownList
.DragBehavior = fmDragBehaviorEnabled
.BorderStyle = fmBorderStyleSingle
.BorderColor = RGB(255, 0, 0)
.MatchEntry = fmMatchEntryComplete
.ListStyle = fmListStyleOption
‘set background color
.BackColor = RGB(216, 216, 216)
‘set font color to blue
.ForeColor = RGB(0, 0, 255)
With .Font
.Name = «Arial»
.Bold = False
.Size = 9
.Italic = False
.Underline = False
End With
‘Populate ComboBox from an Array:
‘create a 2-dimensional array and load to ComboBox using the List property (copies an array without transposing it)
Dim myArray(5, 3)
‘Declaring the array and its dimensions. The array has been named myArray, of size 5 by 3 (5 rows by 3 columns). Note: When you populate an array with data, the array will start at zero, and if you include Option Base 1 the array will start at 1.
‘populate rows & columns of myArray, with worksheet range (rngSource)
For c = 0 To 2
For r = 0 To 5
myArray(r, c) = rngSource(r + 1, c + 1)
Next r
Next c
‘copy data to ComboBox using List property — copies an array without transposing it:
.List() = myArray
‘remove all items if ListFillRange has not been used to fill the combo box
If objCoBx.ListFillRange = «« Then
‘.Clear
‘deleting row from ListBox using RemoveItem method:
For i = .ListCount — 1 To 0 Step -1
.RemoveItem (i)
Next
Else
‘clear ComboBox if filled with ListFillRange/RowSource (if ListFillRange property has been used to specify the source of a list)
objCoBx.ListFillRange = ««
End If
‘ListFillRange property specifies the source of a list (which could be a worksheet range in Excel), for a ComboBox or ListBox.
objCoBx.ListFillRange = rngSource.Address
‘alternatively:
‘objCoBx.ListFillRange = «$A$2:$C$7«
‘objCoBx.ListFillRange = Range(«A2:C7»).Address
‘objCoBx.ListFillRange = «NamedRange«
‘TextColumn property enables display of one set of values to the user but store a different set of values (per column specified in the BoundColumn property).
‘TextColumn property specifies the column of data in a ComboBox that supplies data for its Text property — the TextColumn property determines the column whose value the Text property will return whereas the BoundColumn property determines the column whose value the Value property returns. The Text property returns the same as Value if the TextColumn property is not set. Setting the TextColumn value to -1 indicates that the first column with a ColumnWidths value greater than 0 will be displayed. Setting the TextColumn value to 0 returns the ListIndex value (the number of the selected row) in Text Property — this setting is useful if you want to determine the row of the selected item.
.TextColumn = 1
‘BoundColumn Property: Specifies the column from which value is to be stored in a multicolumn ComboBox or ListBox, when a row is selected by the user. First column has a BoundColumn value of 1
‘Setting the BoundColumn value to 0 assigns the value of the ListIndex property (which is the number of the selected row) as the value of the control (ComboBox or ListBox).
.BoundColumn = 4
‘ListIndex Property determines which item is selected in a ComboBox or ListBox. The first item in a list has a ListIndex value of 0, the second item has a value of 1, and so on.
.ListIndex = 2
‘Value Property: For the controls ComboBox and ListBox (value cannot be used with a multi-select ListBox), it is the value in the BoundColumn of the currently selected row (BoundColumn property specifies the column from which value is to be stored in a multicolumn ComboBox or ListBox, when a row is selected by the user).
MsgBox .Value
‘Using the ListCount property with the ListRows property, to set number of rows to display in ComboBox
‘ListCount Property determines the total number of rows in a ListBox or ComboBox.
If .ListCount > 5 Then
‘ListRows Property specifies the maximum number of rows which will display in the list box portion of a ComboBox. The default value is 8. Note: If the actual number of list items exceed this maximum value of the ListRows property, a vertical scroll bar will appear in the list box portion of the ComboBox (and the excess list items can be viewed by scrolling down).
.ListRows = 4
Else
.ListRows = .ListCount
End If
End With
‘size the ComboBox with the resized range
‘set column width in points
.Width = rngComboBox.Resize(rngComboBox.Rows.Count, rngComboBox.Columns.Count + 3).Width
‘Range.Height Property returns or sets the height of the range, in points
.Height = rngComboBox.Height
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
‘enable the object
.Enabled = True
.Activate
End With
End Sub
Macro associated with the Click event of the ComboBox1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (ComboBox1) — refer Image 5c
Private Sub ComboBox1_Click()
‘on clicking / selecting an item in the ActiveX Control ComboBox1 — refer Image 5c
On Error Resume Next
Dim cat As String, str As String, rng As Range, BMI As Single
Set rng = Range(«A10»)
rng.Resize(rng.Rows.Count, rng.Columns.Count + 2).MergeCells = True
‘Body Mass Index formula is — weight in kilograms divided by the square of height in meters: kg/m2
‘BMI Categories:
‘Underweight = <18.5
‘Normal weight = 18.5–24.9
‘Overweight = 25–29.9
‘Obesity = BMI of 30 or greater
‘assign Value property to BMI
BMI = ComboBox1.Object.Value
If BMI < 18.5 Then
cat = «Underweight»
ElseIf BMI < 25 Then
cat = «Normal Weight»
ElseIf BMI < 30 Then
cat = «Overweight»
ElseIf BMI >= 30 Then
cat = «Obese»
End If
With rng
.Interior.Color = vbGreen
.HorizontalAlignment = xlCenter
‘Combobox Text Property gives the Name, & BMI Category (cat) is derived from BMI (Combobox Value Property)
.Value = ComboBox1.Object.Text & » is » & cat
End With
End Sub
Option Button — Form Control or ActiveX Control
OptionButton is used to make one selection from multiple options. It is also referred to as a Radio Button, which chooses one option from a group of mutually exclusive options. If OptionButtons are not grouped, selecting one OptionButton will de-select all other OptionButtons. All OptionsButtons within a specific Group become mutually exclusive and self-contained within that group and do not affect selection of OptionButtons outside that group. Selecting an OptionButton in one group will de-select all other OptionButtons of only that group. The Value property of an OptionButton indicates whether it is selected or not. A True value indicates that the OptionButton is selected, False is the default value and indicates that it is not selected.
CheckBox vs OptionButton: With CheckBox, user can select multiple options, by selecting each CheckBox against which an option is available. OptionButton is used when user is allowed to select only a single option. CheckBox can be used in a singular manner viz. a single CheckBox can be selected or deselected (by clicking itself) indicating whether an option is to be exercised or not. OptionButton on the other hand are used in multiples viz. two or more, to indicate selection of mutually exculsive options. OptionButton gets deselected only on selection of another OptionButton and not by clicking itself.
Below we illustrate, a Form Control OptionButton, and an ActiveX Control OptionButton.
Example: Form Control Option Button:
Use Shapes.AddFormControl Method to create Excel Form Controls (Option Button & Group Box) — this returns a Shape object representing the new control — refer Image 6a
Sub FormControl_OptionButton_GroupBox_Shape_Properties()
‘use Shapes.AddFormControl Method to create Excel Form Controls (Option Button & Group Box) — this returns a Shape object representing the new control — refer Image 6a
Dim shpOptnBtn As Shape, ws As Worksheet, rngOptnBtn As Range, objOptnBtn As OLEObject
Set ws = Sheets(«Sheet1»)
ws.Activate
Set rngOptnBtn = Range(«B2»)
‘delete ActiveX Control OptionButton objects
For Each objOptnBtn In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objOptnBtn.Object) = «OptionButton» Then objOptnBtn.Delete
Next objOptnBtn
‘delete all (Form Control) Option Buttons in worksheet
ws.OptionButtons.Delete
‘delete all (Form Control) group boxes in worksheet
ws.GroupBoxes.Delete
rngOptnBtn.ColumnWidth = 11
rngOptnBtn.RowHeight = 17
‘for an already existing Form Control shape — Option Button, with the name «Option Button 1»
‘Set shpOptnBtn = ws.Shapes(«Option Button 1»)
‘set object variable to the newly added Option Button Form control — position & size the Option Button with the cell assigned to the rngOptnBtn variable
‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):
Set shpOptnBtn = ws.Shapes.AddFormControl(xlOptionButton, Left:=rngOptnBtn.Left, Top:=rngOptnBtn.Top, Width:=rngOptnBtn.Width, Height:=rngOptnBtn.Height)
With shpOptnBtn
‘set a String value as object’s name
.Name = «Option Button 1«
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
‘shape will retain its original proportions when it is resized
.LockAspectRatio = msoTrue
‘wrt to the cell which is under the upper-left corner of the Option Button — enter text in the same row to the left of the Option Button
.TopLeftCell.Offset(0, -1) = «Country«
‘specify caption text
‘TextFrame Property returns a TextFrame object which contains the alignment & anchoring properties for a shape — valid for only a shape having a text frame
.TextFrame.Characters.Text = «USA«
‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).
.AlternativeText = «Click to Select«
‘use the .OLEFormat.Object object to manipulate Display3DShading
.OLEFormat.Object.Display3DShading = False
‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.
With .ControlFormat
.Enabled = True
‘OptionButton will be printed when the document is printed
.PrintObject = True
End With
‘set check box fill / interior
With .Fill
.Visible = msoTrue
.Solid
‘set background color to yellow
‘.ForeColor.SchemeColor = 13
.ForeColor.RGB = RGB(255, 255, 0)
.Transparency = 0
End With
‘set border for OptionButton
With .Line
.Weight = 1
.DashStyle = msoLineSolid
.Style = msoLineSingle
.Transparency = 0
.Visible = msoTrue
‘.ForeColor.SchemeColor = 10
.ForeColor.RGB = RGB(255, 0, 0)
End With
End With
‘————————————-
‘create second option button (by copying the first)
‘copy OptionButton and create new OptionButton with same properties
‘set range size, for cell below the existing OptionButton
rngOptnBtn.Offset(1, 0).RowHeight = rngOptnBtn.Height
‘copy check box to clipboard
ws.Shapes(«Option Button 1»).Copy
‘paste a copy of the OptionButton in the same sheet
ws.Paste
‘fit new OptionButton in the cell below the existing OptionButton
Selection.Left = rngOptnBtn.Offset(1, 0).Left
Selection.Top = rngOptnBtn.Offset(1, 0).Top
Selection.Name = «Option Button 2«
Selection.Characters.Text = «Canada«
‘alternatively
‘Selection.Caption = «Canada«
‘merge & format cells to the left of OptionButtons 1 & 2
Union(rngOptnBtn.Offset(0, -1), rngOptnBtn.Offset(1, -1)).Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.ReadingOrder = xlContext
.MergeCells = True
.Interior.Color = RGB(0, 255, 0)
End With
‘———————-
‘create third & fourth option buttons (by copying the first)
‘copy OptionButton and create new OptionButton with same properties
‘set range size, for cell below the existing OptionButton
rngOptnBtn.Offset(3, 0).RowHeight = rngOptnBtn.Height
‘copy OptionButton1 to clipboard
ws.Shapes(«Option Button 1»).Copy
‘paste a copy of the OptionButton in the same sheet
ws.Paste
‘fit new OptionButton in the cell below the existing OptionButton
Selection.Left = rngOptnBtn.Offset(3, 0).Left
Selection.Top = rngOptnBtn.Offset(3, 0).Top
Selection.Name = «Option Button 3«
Selection.Caption = «Spain«
‘wrt to the cell which is under the upper-left corner of the Option Button — enter text in the same row to the left of the Option Button
Selection.TopLeftCell.Offset(0, -1) = «Country«
‘copy OptionButton and create new OptionButton with same properties
‘set range size, for cell below the existing OptionButton
rngOptnBtn.Offset(4, 0).RowHeight = rngOptnBtn.Height
‘copy OptionButton3 to clipboard
ws.Shapes(«Option Button 3»).Copy
‘paste a copy of the OptionButton in the same sheet
ws.Paste
‘fit new OptionButton in the cell below the existing OptionButton
Selection.Left = rngOptnBtn.Offset(4, 0).Left
Selection.Top = rngOptnBtn.Offset(4, 0).Top
Selection.Name = «Option Button 4«
Selection.Caption = «France«
‘merge & format cells to the left of OptionButtons 3 & 4
Union(rngOptnBtn.Offset(3, -1), rngOptnBtn.Offset(4, -1)).Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.ReadingOrder = xlContext
.MergeCells = True
.Interior.Color = RGB(0, 255, 0)
End With
‘———————-
‘create 2 (Form Control) group boxes, to include 2 option buttons each
Dim rngGB1 As Range, rngGB2 As Range
‘resize the range for group box to include the range of first & second option buttons
Set rngGB1 = rngOptnBtn.Resize(rngOptnBtn.Rows.Count + 1, rngOptnBtn.Columns.Count)
‘resize the range for group box to include the the range of third & fourth option buttons
Set rngGB2 = rngOptnBtn.Offset(3, 0).Resize(rngOptnBtn.Rows.Count + 1, rngOptnBtn.Columns.Count)
‘add first Group Box — position & size the group box to include the option buttons 1 & 2
With ws.GroupBoxes.Add(Left:=rngGB1.Left, Top:=rngGB1.Top, Width:=rngGB1.Width, Height:=rngGB1.Height)
‘set group box name
.Name = «America«
‘do not display caption
.Characters.Text = ««
.Placement = xlFreeFloating
End With
‘add second Group Box — position & size the group box to include the option buttons 3 & 4
With ws.GroupBoxes.Add(Left:=rngGB2.Left, Top:=rngGB2.Top, Width:=rngGB2.Width, Height:=rngGB2.Height)
.Name = «Europe«
.Characters.Text = ««
.Placement = xlFreeFloating
End With
‘enter in the cell to the left of option buttons 1 & 3
ws.Shapes(«Option Button 1»).TopLeftCell.Offset(0, -1).Value = ws.GroupBoxes(1).Name
ws.Shapes(«Option Button 3»).TopLeftCell.Offset(0, -1).Value = ws.GroupBoxes(2).Name
‘you may use the same linked cell for all option buttons within a group, because the linked cell returns the number of the selected option button within in the group viz. the first option button within a group returns 1, the second option button returns 2, and so on. For multiple groups on a worksheet, use a different linked cell for each group of option buttons.
ws.Shapes(«Option Button 1»).ControlFormat.linkedCell = rngOptnBtn.Address
ws.Shapes(«Option Button 2»).ControlFormat.linkedCell = rngOptnBtn.Address
ws.Shapes(«Option Button 3»).ControlFormat.linkedCell = rngOptnBtn.Offset(3, 0).Address
ws.Shapes(«Option Button 4»).ControlFormat.linkedCell = rngOptnBtn.Offset(3, 0).Address
‘Value property of a OptionButton indicates whether it is selected or not.
‘select option buttons 1 & 4
ws.Shapes(«Option Button 1»).ControlFormat.Value = xlOn
ws.Shapes(«Option Button 4»).ControlFormat.Value = xlOn
Dim str As String
‘————————————
‘return the selected OptionButton’s caption & its GroupBox’ name — alternate 1:
‘Form Control OptionButton objects
‘For Each shpOptnBtn In ActiveSheet.Shapes
‘If shpOptnBtn.FormControlType = xlOptionButton Then
‘if option button is 1 or 2, & if selected
‘If (shpOptnBtn.Name = «Option Button 1» Or shpOptnBtn.Name = «Option Button 2») And shpOptnBtn.ControlFormat.Value = xlOn Then
‘return the selected OptionButton’s caption & its GroupBox’ name
‘str = str & «; » & shpOptnBtn.TextFrame.Characters.Text & » in » & ws.GroupBoxes(1).Name
‘End If
‘if option button is 3 or 4, & if selected
‘If (shpOptnBtn.Name = «Option Button 3» Or shpOptnBtn.Name = «Option Button 4») And shpOptnBtn.ControlFormat.Value = xlOn Then
‘return the selected OptionButton’s caption & its GroupBox’ name
‘str = str & «; » & shpOptnBtn.TextFrame.Characters.Text & » in » & ws.GroupBoxes(2).Name
‘End If
‘End If
‘Next
‘————————————
‘return the selected OptionButton’s caption & its GroupBox’ name — alternate 2:
‘Form Control OptionButton objects
For Each shpOptnBtn In ActiveSheet.Shapes
If shpOptnBtn.FormControlType = xlOptionButton Then
‘if option button range intersects with group box 1 range (ie. if option button is 1 or 2), & if selected
If Not Intersect(shpOptnBtn.TopLeftCell, rngGB1) Is Nothing And shpOptnBtn.ControlFormat.Value = 1 Then
‘return the selected OptionButton’s caption & its GroupBox’ name
str = str & «; » & shpOptnBtn.TextFrame.Characters.Text & » in » & ws.GroupBoxes(1).Name
End If
‘if option button range intersects with group box 2 range (ie. if option button is 3 or 4), & if selected
If Not Intersect(shpOptnBtn.TopLeftCell, rngGB2) Is Nothing And shpOptnBtn.ControlFormat.Value = 1 Then
‘return the selected OptionButton’s caption & its GroupBox’ name
str = str & «; » & shpOptnBtn.TextFrame.Characters.Text & » in » & ws.GroupBoxes(2).Name
End If
End If
Next
‘delete starting «;»
‘return the caption & group name of Selected option buttons
If Left(str, 1) = «;» Then
‘returns: «USA in America; France in Europe»
str = Right(str, Len(str) — 2)
MsgBox str
Else
MsgBox str
End If
End Sub
Example: ActiveX Control Option Button:
Add a new OLEObject to a sheet — ActiveX control (OptionButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object, set GroupName for Option Buttons — refer Image 6b
Sub ActiveXControl_OptionButton_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (OptionButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 6b
‘set a group name — OptionButtons having the same GroupName become mutually exclusive and selecting one OptionButton will de-select all other OptionButtons of that group
Dim ws As Worksheet, rngOptnBtn As Range
‘OLEObject is not used for Form Controls
Dim objOptnBtn As OLEObject
Set ws = Sheets(«Sheet1»)
ws.Activate
‘set range/cell for OptionButton
Set rngOptnBtn = Range(«B2»)
‘delete ActiveX Control OptionButton objects
For Each objOptnBtn In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objOptnBtn.Object) = «OptionButton» Then objOptnBtn.Delete
Next objOptnBtn
‘delete Form Control OptionButton objects
Dim sh As Shape
For Each sh In ActiveSheet.Shapes
If sh.Type = msoFormControl Then
If sh.FormControlType = xlOptionButton Then sh.Delete
End If
Next sh
‘delete all (Form Control) group boxes in worksheet
ws.GroupBoxes.Delete
rngOptnBtn.ColumnWidth = 11
rngOptnBtn.RowHeight = 17
‘for an already existing ActiveX control OptionButton, with the name «OptionButton1»
‘Set objOptnBtn = ws.OLEObjects(«OptionButton1»)
‘set object variable to the newly added OptionButton ActiveX control — position & size the OptionButton with the cell assigned to the rngOptnBtn variable
Set objOptnBtn = ws.OLEObjects.Add(ClassType:=»Forms.OptionButton.1«, DisplayAsIcon:=False, Left:=rngOptnBtn.Left, Top:=rngOptnBtn.Top, Width:=rngOptnBtn.Width, Height:=rngOptnBtn.Height)
With objOptnBtn
‘set a String value as object’s name
.Name = «OptionButton1«
‘returns the index number of the object within the collection of similar objects
‘MsgBox .Index
‘set shadow
.Shadow = True
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
.Enabled = True
‘OptionButton will be printed when the document is printed
.PrintObject = True
‘LinkedCell Property specifies a cell to set or store the Value property — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.
‘.LinkedCell = «Sheet1!B2«
.linkedCell = rngOptnBtn.Address
‘wrt to the cell which is under the upper-left corner of the option button — enter text in the same row to the left of the option button
.TopLeftCell.Offset(0, -1) = «Country«
‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object
‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object
With .Object
.TextAlign = fmTextAlignCenter
‘TripleState property if set to True, will enable OptionButton to have three possible values, including the Null value, besides True & False
.TripleState = False
‘Value property of a OptionButton indicates whether it is selected or not. True (integer value 1) indicates that the OptionButton is selected, False (value of 0) indicates that it is cleared; and the Null value indicates that it is neither selected nor cleared, and the OptionButton will appear shaded in this case. The value of TripleState property should be set to True for the OptionButton to have a Null value.
.Value = False
‘determines how the control visually appears
.SpecialEffect = fmButtonEffectFlat
‘specify how caption will appear relative to the control
.Alignment = fmAlignmentLeft
‘Accelerator Property sets the key to access a control
.Accelerator = «h«
‘specify type of mouse pointer
.MousePointer = fmMousePointerArrow
‘load a picture to be displayed on the ActiveX control
.Picture = LoadPicture(«C:UsersamitDocumentsPhotosDollar.jpg»)
‘alignment of the picture with its caption
.PicturePosition = fmPicturePositionAboveCenter
‘remove picture
.Picture = LoadPicture(«»)
‘specify caption text
.Caption = «USA«
‘caption text will wrap to the next line
.WordWrap = True
‘setting AutoSize to True automatically resizes the Caption while False (Default option) keeps the caption size constant wherein content exceeding the control area gets cut.
.AutoSize = False
‘set background color to yellow
.BackColor = RGB(255, 255, 0)
‘set font color to red
.ForeColor = RGB(255, 0, 0)
‘set background to be Opaque or Transparent — BackStyle property should be set to fmBackStyleOpaque for the BackColor to have any effect
.BackStyle = fmBackStyleOpaque
With .Font
.Name = «Arial»
.Bold = True
.Size = 10
.Italic = False
.Underline = False
End With
End With
End With
‘———————-
‘copy OptionButton and create new OptionButton with same properties
‘set range size, for cell below the existing OptionButton
rngOptnBtn.Offset(1, 0).ColumnWidth = rngOptnBtn.ColumnWidth
rngOptnBtn.Offset(1, 0).RowHeight = rngOptnBtn.Height
‘copy OptionButton1 to clipboard
ws.OLEObjects(«OptionButton1»).Copy
‘paste a copy of the OptionButton in the same sheet
ws.Paste
‘fit new OptionButton in the cell below the existing OptionButton
Selection.Left = rngOptnBtn.Offset(1, 0).Left
Selection.Top = rngOptnBtn.Offset(1, 0).Top
Selection.Name = «OptionButton2«
ws.OLEObjects(«OptionButton2»).linkedCell = rngOptnBtn.Offset(1, 0).Address
ws.OLEObjects(«OptionButton2»).Object.Caption = «Canada«
‘merge & format cells to the left of both OptionButtons
Union(rngOptnBtn.Offset(0, -1), rngOptnBtn.Offset(1, -1)).Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.ReadingOrder = xlContext
.MergeCells = True
.Interior.Color = RGB(0, 255, 0)
End With
‘———————-
‘copy OptionButton and create new OptionButton with same properties
‘set range size, for cell below the existing OptionButton
rngOptnBtn.Offset(3, 0).ColumnWidth = rngOptnBtn.ColumnWidth
rngOptnBtn.Offset(3, 0).RowHeight = rngOptnBtn.Height
‘copy OptionButton1 to clipboard
ws.OLEObjects(«OptionButton1»).Copy
‘paste a copy of the OptionButton in the same sheet
ws.Paste
‘fit new OptionButton in the cell below the existing OptionButton
Selection.Left = rngOptnBtn.Offset(3, 0).Left
Selection.Top = rngOptnBtn.Offset(3, 0).Top
Selection.Name = «OptionButton3»
ws.OLEObjects(«OptionButton3»).linkedCell = rngOptnBtn.Offset(3, 0).Address
ws.OLEObjects(«OptionButton3»).Object.Caption = «Spain«
‘wrt to the cell which is under the upper-left corner of the option button
ws.OLEObjects(«OptionButton3»).TopLeftCell.Offset(0, -1) = «Country«
‘copy OptionButton and create new OptionButton with same properties
‘set range size, for cell below the existing OptionButton
rngOptnBtn.Offset(4, 0).ColumnWidth = rngOptnBtn.ColumnWidth
rngOptnBtn.Offset(4, 0).RowHeight = rngOptnBtn.Height
‘copy OptionButton3 to clipboard
ws.OLEObjects(«OptionButton3»).Copy
‘paste a copy of the OptionButton in the same sheet
ws.Paste
‘fit new OptionButton in the cell below the existing OptionButton
Selection.Left = rngOptnBtn.Offset(4, 0).Left
Selection.Top = rngOptnBtn.Offset(4, 0).Top
Selection.Name = «OptionButton4»
ws.OLEObjects(«OptionButton4»).linkedCell = rngOptnBtn.Offset(4, 0).Address
ws.OLEObjects(«OptionButton4»).Object.Caption = «France»
‘merge & format cells to the left of OptionButtons 3 & 4
Union(rngOptnBtn.Offset(3, -1), rngOptnBtn.Offset(4, -1)).Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.ReadingOrder = xlContext
.MergeCells = True
.Interior.Color = RGB(0, 255, 0)
End With
‘———————-
‘use the GroupName property to set a group name for an option button — OptionButtons having the same GroupName become mutually exclusive and selecting one OptionButton will de-select all other OptionButtons of that group
ws.OLEObjects(«OptionButton1»).Object.GroupName = «America«
ws.OLEObjects(«OptionButton2»).Object.GroupName = «America«
ws.OLEObjects(«OptionButton3»).Object.GroupName = «Europe«
ws.OLEObjects(«OptionButton4»).Object.GroupName = «Europe«
‘enter group names on the left of option buttons
ws.OLEObjects(«OptionButton1»).TopLeftCell.Offset(0, -1) = «America«
ws.OLEObjects(«OptionButton3»).TopLeftCell.Offset(0, -1) = «Europe«
‘select option buttons 2 & 4
ws.OLEObjects(«OptionButton2»).Object = True
ws.OLEObjects(«OptionButton4»).Object = True
Dim str As String
‘ActiveX Control OptionButton objects
For Each objOptnBtn In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objOptnBtn.Object) = «OptionButton» Then
If objOptnBtn.Object.GroupName = «America» And objOptnBtn.Object.Value = True Then
str = str & «; » & objOptnBtn.Object.Caption & » in America»
End If
If objOptnBtn.Object.GroupName = «Europe» And objOptnBtn.Object.Value = True Then
str = str & «; » & objOptnBtn.Object.Caption & » in Europe»
End If
End If
Next
‘delete starting «;»
‘return the caption & group name of Selected option buttons
If Left(str, 1) = «;» Then
‘returns: «USA in America; France in Europe»
str = Right(str, Len(str) — 2)
rngOptnBtn.Offset(6, -1).Value = str
Else
rngOptnBtn.Offset(6, -1).Value = str
End If
End Sub
Toggle Button — ActiveX Control
ToggleButton is a control which executes one action when clicked first and a different action on the second click. It has two states, On & Off, wherein the button alternates (or toggles) between the two. It can have a value of True (where it appears as pressed) when the button is selected or the value False (appears unpressed) when unselected.
Below we illustrate an ActiveX Control ToggleButton a Macro associated with the Click event of this ToggleButton.
Example: ActiveX Control Toggle Button:
Add a new OLEObject to a sheet — ActiveX control (ToggleButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 7a
Sub ActiveXControl_ToggleButton_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (ToggleButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 7a
Dim ws As Worksheet, rngTglBtn As Range
‘OLEObject is not used for Form Controls
Dim objTglBtn As OLEObject
Set ws = Sheets(«Sheet1»)
ws.Activate
‘set range/cell for ToggleButton
Set rngTglBtn = Range(«B2»)
‘delete ActiveX Control ToggleButton objects
For Each objTglBtn In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objTglBtn.Object) = «ToggleButton» Then objTglBtn.Delete
Next objTglBtn
rngTglBtn.ColumnWidth = 22
rngTglBtn.RowHeight = 24
‘for an already existing ActiveX control ToggleButton, with the name «ToggleButton1»
‘Set objTglBtn = ws.OLEObjects(«ToggleButton1»)
‘set object variable to the newly added ToggleButton ActiveX control — position & size the ToggleButton with the cell assigned to the rngTglBtn variable
Set objTglBtn = ws.OLEObjects.Add(ClassType:=»Forms.ToggleButton.1«, DisplayAsIcon:=False, Left:=rngTglBtn.Left, Top:=rngTglBtn.Top, Width:=rngTglBtn.Width, Height:=rngTglBtn.Height)
With objTglBtn
‘set a String value as object’s name
.Name = «ToggleButton1«
‘set shadow
.Shadow = True
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
.Enabled = True
‘toggle buttonwill be printed when the document is printed
.PrintObject = True
‘LinkedCell Property specifies a cell to set or store the Value property — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.
‘TopLeftCell — wrt to the cell which is under the upper-left corner of the toggle button
.linkedCell = .TopLeftCell.Offset(0, -1).Address
‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object
‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object
With .Object
.TextAlign = fmTextAlignCenter
‘TripleState property if set to True, will enable ToggleButton to have three possible values, including the Null value, besides True & False
.TripleState = False
‘Value property of a ToggleButton indicates whether it is selected or not. True (integer value 1) indicates that the ToggleButton is selected & where it appears as pressed, False (value of 0) indicates that it is unselected where it appears as unpressed; and the Null value indicates that it is neither selected nor cleared, and the ToggleButton will appear shaded in this case. The value of TripleState property should be set to True for the ToggleButton to have a Null value.
.Value = False
‘Accelerator Property sets the key to access a control
.Accelerator = «h«
‘specify type of mouse pointer
.MousePointer = fmMousePointerArrow
‘load a picture into ActiveX control, using the LoadPicture Function — specify filename & address of image to be loaded
.Picture = LoadPicture(«C:UsersamitDocumentsPhotosDollar.jpg»)
‘alignment of the picture with its caption
.PicturePosition = fmPicturePositionAboveCenter
‘remove picture
.Picture = LoadPicture(«»)
‘specify caption text
.Caption = «Sort Data«
‘caption text will wrap to the next line
.WordWrap = True
‘setting AutoSize to True automatically resizes the Caption while False (Default option) keeps the caption size constant wherein content exceeding the control area gets cut.
.AutoSize = False
‘set the background color for control to yellow
.BackColor = RGB(255, 255, 0)
‘set font color to black
.ForeColor = RGB(0, 0, 0)
‘set background to be Opaque or Transparent — BackStyle property should be set to fmBackStyleOpaque for the BackColor to have any effect
.BackStyle = fmBackStyleOpaque
With .Font
.Name = «Arial«
.Bold = True
.Size = 10
.Italic = True
.Underline = False
End With
End With
End With
End Sub
Macro associated with the Click event of the ToggleButton1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (ToggleButton1) — refer Image 7b
Private Sub ToggleButton1_Click()
‘ToggleButton control generates a Click event for which an event-handler sub procedure has been written here — refer Image 7b
‘ToggleButton is a control which executes one action when clicked first and a different action on the second click. It has two states, On & Off, wherein the button alternates (or toggles) between the two. It can have a value of True (where it appears as pressed) when the button is selected or the value False (appears unpressed) when unselected.
Dim lTotalRows As Long, ws As Worksheet
‘determine total rows in column D:
lTotalRows = Cells(Rows.Count, «D»).End(xlUp).Row
‘if ToggleButton value is True: it appears pressed — data in column D appears sorted in Descending order — button appears in green BackColor and displays the alternate sort option («Get Ascending Order»):
If ToggleButton1.Value = True Then
ToggleButton1.Caption = «Get Ascending Order«
ToggleButton1.BackColor = RGB(0, 255, 0)
Range(«D2:D» & lTotalRows).Sort key1:=Range(«D2»), order1:=xlDescending
‘if ToggleButton value is False: it appears unpressed — data in column D appears sorted in Ascending order — button appears in red BackColor and displays the alternate sort option («Get Decending Order»):
ElseIf ToggleButton1.Value = False Then
ToggleButton1.Caption = «Get Decending Order«
ToggleButton1.BackColor = RGB(255, 0, 0)
Range(«D2:D» & lTotalRows).Sort key1:=Range(«D2»), order1:=xlAscending
End If
End Sub
ScrollBar & SpinButton Controls — Form Control or ActiveX Control
A ScrollBar control enables to scroll through a range of values when a user: (i) clicks on the scroll arrows; (ii) drags the scroll box; or (iii) clicks in an area between a scroll arrow and the scroll box. Both ScrollBar control & SpinButton control enable to change (increment or decrement) value in a worksheet range. SpinButton control (also referred to as a Spinner control) functions like a ScrollBar control, with similar properties (viz. SmallChange, Min, Max, Orientation, …). Difference between the ScrollBar & SpinButton controls is that the ScrollBar box can be dragged to change the control’s value over larger increments (while keeping the increment low for clicks) which advantages a ScrollBar to make a selection from across a large number of values and cover an extremely wide range. SpinButton control does not have a LargeChange property, like in a ScrollBar, which specifies the incremental change when the user clicks between a scroll arrow and the scroll box.
Below we illustrate: (i) a Form Control Scroll Bar & and assign it to a Macro; and (ii) an ActiveX Control ScrollBar & Macro associated with the Change event of this ScrollBar.
Example: Form Control Scroll Bar & Macro to which it is assigned:
Create an Excel Form Control (Scroll Bar) & set ScrollBar properties — use Shapes.AddFormControl Method to create an Excel Form Control which returns a Shape object representing the new control — Refer Image 8a
Sub FormControl_ScrollBar_Shape_Properties()
‘use Shapes.AddFormControl Method to create an Excel Form Control (ScrollBar) — this returns a Shape object representing the new control — refer Image 8a
‘Creating a Mortgage Calculator, using ScrollBar controls: Loan Amount ($)in cell B2 & its «Scroll Bar 1» in cell C2; Annual Interest (%) in cell B3 & its «Scroll Bar 2» in cell C3; Loan Tenure (Yrs) in cell B4 & its «Scroll Bar 3» in cell C4; Mthly Instalment ($) in cell B5.
Dim ws As Worksheet, shpScrlBar As Shape, objScrlBar As OLEObject
Dim rngScrlBar1 As Range, rngScrlBar2 As Range, rngScrlBar3 As Range
Set ws = Sheets(«Sheet1»)
ws.Activate
‘set range/cell for ScrollBar
Set rngScrlBar1 = Range(«C2»)
Set rngScrlBar2 = Range(«C3»)
Set rngScrlBar3 = Range(«C4»)
‘format cells
With rngScrlBar1.Offset(0, -1).Resize(1, 2)
.Value = ««
.NumberFormat = «$#,##0«
End With
With rngScrlBar2.Offset(0, -1).Resize(2, 2)
.Value = ««
.NumberFormat = «0.0«
End With
With rngScrlBar3.Offset(1, -1)
.Value = «»
.NumberFormat = «$#,##0«
End With
‘delete ActiveX Control ScrollBar objects
For Each objScrlBar In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objScrlBar.Object) = «ScrollBar» Then objScrlBar.Delete
Next objScrlBar
‘delete Form Control ScrollBar objects
For Each shpScrlBar In ActiveSheet.Shapes
If shpScrlBar.Type = msoFormControl Then
If shpScrlBar.FormControlType = xlScrollBar Then shpScrlBar.Delete
End If
Next shpScrlBar
rngScrlBar1.ColumnWidth = 15
rngScrlBar1.RowHeight = 15
‘for an already existing Form Control shape — ScrollBar, with the name «Scroll Bar 1»
‘Set shpScrlBar = ws.Shapes(«Scroll Bar 1»)
‘set object variable to the newly added check box Form control — position & size the ScrollBar with the cell assigned to the rngScrlBar1 variable
‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):
‘a scroll bar gets oriented (horizontal or vertical) based on its size on the worksheet, whereas an ActiveX scroll bar has an Orientation property which can be set to be Auto, Horizontal, or Vertical
Set shpScrlBar = ws.Shapes.AddFormControl(xlScrollBar, Left:=rngScrlBar1.Left, Top:=rngScrlBar1.Top, Width:=rngScrlBar1.Width, Height:=rngScrlBar1.Height)
With shpScrlBar
‘set a String value as object’s name
.Name = «Scroll Bar 1«
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
‘shape will retain its original proportions when it is resized
.LockAspectRatio = msoTrue
‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).
.AlternativeText = «Scroll«
‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ScrollBar_CalcPMT macro
.OnAction = «ScrollBar_CalcPMT«
‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.
With .ControlFormat
.Enabled = True
‘scroll bar will be printed when the document is printed
.PrintObject = True
‘LinkedCell Property specifies a cell to set or store the Value property ie. the current value corresponding to the position of the scroll box — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.
.linkedCell = rngScrlBar1.Address
‘specify the minimum and maximum acceptable values (as integer) of the ScrollBar control (for the Value property setting), value of the Max property must be greater than the value of the Min property
.Min = 0
.Max = 10000
‘SmallChange Property specifies the incremental change, as an integer value, that occurs when a user clicks the scroll arrow. Default value is 1.
.SmallChange = 5
‘LargeChange Property specifies the incremental change, as an integer value, when the user clicks between a scroll arrow and the scroll box. Default value is 1.
.LargeChange = 100
‘Value property sets the control’s current value, which is an integer between maximum & minimum values specified in the Max and Min properties
.Value = 1000
End With
End With
‘———————-
‘2nd ScrollBar: copy ScrollBar and create second ScrollBar with same properties
‘set range size, for cell below the existing ScrollBar
rngScrlBar2.ColumnWidth = rngScrlBar1.ColumnWidth
rngScrlBar2.RowHeight = rngScrlBar1.Height
‘copy ScrollBar1 to clipboard
ws.Shapes(«Scroll Bar 1»).Copy
‘paste a copy of the ScrollBar in the same sheet
ws.Paste
‘fit new ScrollBar in the cell below the existing ScrollBar
Selection.Left = rngScrlBar2.Left
Selection.Top = rngScrlBar2.Top
Selection.Name = «Scroll Bar 2«
‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ScrollBar_CalcPMT macro
Selection.OnAction = «ScrollBar_CalcPMT«
With ws.Shapes(«Scroll Bar 2»).ControlFormat
.linkedCell = rngScrlBar2.Address
.Min = 0
.Max = 500
.SmallChange = 1
.LargeChange = 10
.Value = 50
End With
‘———————-
‘3rd ScrollBar: copy ScrollBar and create third ScrollBar with same properties
‘set range size, for cell below the existing ScrollBar
rngScrlBar3.ColumnWidth = rngScrlBar1.ColumnWidth
rngScrlBar3.RowHeight = rngScrlBar1.Height
‘copy ScrollBar1 to clipboard
ws.Shapes(«Scroll Bar 1»).Copy
‘paste a copy of the ScrollBar in the same sheet
ws.Paste
‘fit new ScrollBar in the cell below the existing ScrollBar
Selection.Left = rngScrlBar3.Left
Selection.Top = rngScrlBar3.Top
Selection.Name = «Scroll Bar 3«
‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ScrollBar_CalcPMT macro
Selection.OnAction = «ScrollBar_CalcPMT«
With ws.Shapes(«Scroll Bar 3»).ControlFormat
.linkedCell = rngScrlBar3.Address
.Min = 0
.Max = 60
.SmallChange = 1
.LargeChange = 4
.Value = 20
End With
‘calculate monthly instalment in cell B5, by calling the macro ScrollBar_CalcPMT:
Call ScrollBar_CalcPMT
End Sub
This macro ( located in a standard module of the workbook) has been assigned to the scroll bars — «Scroll Bar 1» & «Scroll Bar 2» & «Scroll Bar 3» — & will execute when respective scrollbar value changes — refer Image 8a.
Sub ScrollBar_CalcPMT()
‘this macro has been assigned to the scroll bars — «Scroll Bar 1» & «Scroll Bar 2» & «Scroll Bar 3» — & will execute when respective scrollbar value changes — refer Image 8a
‘Creating a Mortgage Calculator, using ScrollBar controls: Loan Amount ($) in cell B2 & its «Scroll Bar 1» in cell C2; Annual Interest (%) in cell B3 & its «Scroll Bar 2» in cell C3; Loan Tenure (Yrs) in cell B4 & its «Scroll Bar 3» in cell C4; Mthly Instalment ($) in cell B5.
Dim ws As Worksheet, shpScrlBar1 As Shape, shpScrlBar2 As Shape, shpScrlBar3 As Shape
Dim rngScrlBar1 As Range, rngScrlBar2 As Range, rngScrlBar3 As Range
Set ws = Sheets(«Sheet1»)
ws.Activate
Set shpScrlBar1 = ws.Shapes(«Scroll Bar 1»)
Set shpScrlBar2 = ws.Shapes(«Scroll Bar 2»)
Set shpScrlBar3 = ws.Shapes(«Scroll Bar 3»)
‘set range/cell for ScrollBar
‘cell C2
Set rngScrlBar1 = Range(shpScrlBar1.ControlFormat.linkedCell)
‘cell C3
Set rngScrlBar2 = Range(shpScrlBar2.ControlFormat.linkedCell)
‘cell C4
Set rngScrlBar3 = Range(shpScrlBar3.ControlFormat.linkedCell)
‘in re of Loan Amount, clicking the scroll arrow will increment amount by $5,000 and clicking between a scroll arrow and the scroll box will increment amount by $100,000:
rngScrlBar1.Offset(0, -1).Value = shpScrlBar1.ControlFormat.Value * 1000
‘in re of Annual Interest Rate, clicking the scroll arrow will increment rate by 0.1% and clicking between a scroll arrow and the scroll box will increment rate by 1%:
rngScrlBar2.Offset(0, -1).Value = shpScrlBar2.ControlFormat.Value / 10
‘in re of Loan Tenure, clicking the scroll arrow will increment year by 0.5 and clicking between a scroll arrow and the scroll box will increment year by 2:
rngScrlBar3.Offset(0, -1).Value = shpScrlBar3.ControlFormat.Value / 2
If Not rngScrlBar1.Offset(0, -1).Value > 0 Then
MsgBox «Please Enter Loan Amount!»
Exit Sub
ElseIf Not rngScrlBar2.Offset(0, -1).Value > 0 Then
MsgBox «Please Enter Annual Interest Rate!»
Exit Sub
ElseIf Not rngScrlBar3.Offset(0, -1).Value > 0 Then
MsgBox «Please Enter Loan Tenure!»
Exit Sub
End If
‘calculate monthly instalment in cell B5:
rngScrlBar3.Offset(1, -1).Value = Pmt((rngScrlBar2.Offset(0, -1).Value / 100) / 12, rngScrlBar3.Offset(0, -1).Value * 12, rngScrlBar1.Offset(0, -1).Value) * -1
End Sub
Example: ActiveX Control ScrollBar(s) & Macro associated with the Change event of the ScrollBar(s):
Add a new OLEObject to a sheet — ActiveX control (ScrollBar) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 8b
Sub ActiveXControl_ScrollBar_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (ScrollBar) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 8b
‘ScrollBar control enables to change (increment or decrement) value in a worksheet range
‘Creating a Mortgage Calculator, using ScrollBar controls: Loan Amount ($)in cell B2 & its ScrollBar1 in cell C2; Annual Interest (%) in cell B3 & its ScrollBar2 in cell C3; Loan Tenure (Yrs) in cell B4 & its ScrollBar3 in cell C4; Mthly Instalment ($) in cell B5.
Dim ws As Worksheet, rngScrlBar1 As Range, rngScrlBar2 As Range, rngScrlBar3 As Range
‘OLEObject is not used for Form Controls
Dim objScrlBar As OLEObject
Set ws = Sheets(«Sheet1»)
ws.Activate
‘set range/cell for ScrollBar
Set rngScrlBar1 = Range(«C2»)
Set rngScrlBar2 = Range(«C3»)
Set rngScrlBar3 = Range(«C4»)
With rngScrlBar1.Offset(0, -1).Resize(1, 2)
.Value = ««
.NumberFormat = «$#,##0«
End With
With rngScrlBar2.Offset(0, -1).Resize(2, 2)
.Value = ««
.NumberFormat = «0.0«
End With
With rngScrlBar3.Offset(1, -1)
.Value = «»
.NumberFormat = «$#,##0«
End With
‘delete ActiveX Control ScrollBar objects
For Each objScrlBar In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objScrlBar.Object) = «ScrollBar» Then objScrlBar.Delete
Next objScrlBar
‘delete all (Form Control) Scroll Bars in worksheet
ws.ScrollBars.Delete
rngScrlBar1.ColumnWidth = 15
rngScrlBar1.RowHeight = 15
‘for an already existing ActiveX control ScrollBar, with the name «ScrollBar1»
‘Set objScrlBar = ws.OLEObjects(«ScrollBar1»)
‘set object variable to the newly added ScrollBar ActiveX control — position & size the ScrollBar with the cell assigned to the rngScrlBar1 variable
Set objScrlBar = ws.OLEObjects.Add(ClassType:=»Forms.ScrollBar.1«, DisplayAsIcon:=False, Left:=rngScrlBar1.Left, Top:=rngScrlBar1.Top, Width:=rngScrlBar1.Width, Height:=rngScrlBar1.Height)
With objScrlBar
‘set a String value as object’s name
.Name = «ScrollBar1»
‘set shadow
.Shadow = True
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
.Enabled = True
‘scroll bar will be printed when the document is printed
.PrintObject = True
‘LinkedCell Property specifies a cell to set or store the Value property — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.
.linkedCell = rngScrlBar1.Address
‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object
‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object
With .Object
‘specify the minimum and maximum acceptable values (as integer) of the ScrollBar control (for the Value property setting)
.Min = 0
.Max = 10000
‘Orientation Property determines a vertical ScrollBar or a horizontal ScrollBar. It has 3 settings: (i) fmOrientationAuto (Value -1, default) — ScrollBar dimensions automatically determine whether the ScrollBar is Vertical or Horizontal. Where width is more than height, ScrollBar is Horizontal and where height is more than width, ScrollBar is Vertical; (ii) FmOrientationVertical (Value 0) — vertical ScrollBar; and (iii) FmOrientationHorizontal (Value 1) — horizontal ScrollBar.
.Orientation = fmOrientationHorizontal
‘SmallChange Property specifies the incremental change, as an integer value, that occurs when a user clicks the scroll arrow. Default value is 1.
.SmallChange = 5
‘LargeChange Property specifies the incremental change, as an integer value, when the user clicks between a scroll arrow and the scroll box. Default value is 1.
.LargeChange = 100
‘Value property sets the control’s current value, which is an integer between maximum & minimum values specified in the Max and Min properties
.Value = 0
‘specify type of mouse pointer
.MousePointer = fmMousePointerArrow
‘set background color to yellow
.BackColor = RGB(255, 255, 0)
‘set scroll arrow color to red
.ForeColor = RGB(255, 0, 0)
End With
End With
‘———————-
‘2nd ScrollBar: copy ScrollBar and create new ScrollBar with same properties
‘set range size, for cell below the existing ScrollBar
rngScrlBar2.ColumnWidth = rngScrlBar1.ColumnWidth
rngScrlBar2.RowHeight = rngScrlBar1.Height
‘copy ScrollBar1 to clipboard
ws.OLEObjects(«ScrollBar1»).Copy
‘paste a copy of the ScrollBar in the same sheet
ws.Paste
‘fit new ScrollBar in the cell below the existing ScrollBar
Selection.Left = rngScrlBar2.Left
Selection.Top = rngScrlBar2.Top
Selection.Name = «ScrollBar2«
ws.OLEObjects(«ScrollBar2»).linkedCell = rngScrlBar2.Address
With ws.OLEObjects(«ScrollBar2»).Object
.Min = 0
.Max = 500
.SmallChange = 1
.LargeChange = 10
.Value = 0
End With
‘———————-
‘3rd ScrollBar: copy ScrollBar and create new ScrollBar with same properties
‘set range size, for cell below the existing ScrollBar
rngScrlBar3.ColumnWidth = rngScrlBar1.ColumnWidth
rngScrlBar3.RowHeight = rngScrlBar1.Height
‘copy ScrollBar1 to clipboard
ws.OLEObjects(«ScrollBar1»).Copy
‘paste a copy of the ScrollBar in the same sheet
ws.Paste
‘fit new ScrollBar in the cell below the existing ScrollBar
Selection.Left = rngScrlBar3.Left
Selection.Top = rngScrlBar3.Top
Selection.Name = «ScrollBar3«
ws.OLEObjects(«ScrollBar3»).linkedCell = rngScrlBar3.Address
With ws.OLEObjects(«ScrollBar3»).Object
.Min = 0
.Max = 60
.SmallChange = 1
.LargeChange = 4
.Value = 0
End With
End Sub
Macro associated with the Change event of the ScrollBar1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (ScrollBar1)
Private Sub ScrollBar1_Change()
‘Loan Amount ($) in cell B2 & its ScrollBar1 in cell C2
‘calculate monthly instalment:
Call CalcPMT
End Sub
Macro associated with the Change event of the ScrollBar2: this Event-handler procedure must be located in the code module of the object worksheet containing the control (ScrollBar2)
Private Sub ScrollBar2_Change()
‘Annual Interest (%) in cell B3 & its ScrollBar2 in cell C3
‘calculate monthly instalment:
Call CalcPMT
End Sub
Macro associated with the Change event of the ScrollBar3: this Event-handler procedure must be located in the code module of the object worksheet containing the control (ScrollBar3)
Private Sub ScrollBar3_Change()
‘Loan Tenure (Yrs) in cell B4 & its ScrollBar3 in cell C4
‘calculate monthly instalment:
Call CalcPMT
End Sub
Macro called by the Change events of the 3 ScrollBars: this Event-handler procedure must be located in the code module of the object worksheet containing the controls (ScrollBars) — refer Image 8c.
Sub CalcPMT()
‘Creating a Mortgage Calculator, using ScrollBar controls: Loan Amount ($) in cell B2 & its ScrollBar1 in cell C2; Annual Interest (%) in cell B3 & its ScrollBar2 in cell C3; Loan Tenure (Yrs) in cell B4 & its ScrollBar3 in cell C4; Mthly Instalment ($) in cell B5.
Dim rngScrlBar1 As Range, rngScrlBar2 As Range, rngScrlBar3 As Range
‘set range/cell for ScrollBar
‘cell C2
Set rngScrlBar1 = Range(ScrollBar1.linkedCell)
‘cell C3
Set rngScrlBar2 = Range(ScrollBar2.linkedCell)
‘cell C4
Set rngScrlBar3 = Range(ScrollBar3.linkedCell)
‘in re of Loan Amount, clicking the scroll arrow will increment amount by $5,000 and clicking between a scroll arrow and the scroll box will increment amount by $100,000:
rngScrlBar1.Offset(0, -1).Value = ScrollBar1.Value * 1000
‘in re of Annual Interest Rate, clicking the scroll arrow will increment rate by 0.1% and clicking between a scroll arrow and the scroll box will increment rate by 1%:
rngScrlBar2.Offset(0, -1).Value = ScrollBar2.Value / 10
‘in re of Loan Tenure, clicking the scroll arrow will increment year by 0.5 and clicking between a scroll arrow and the scroll box will increment year by 2:
rngScrlBar3.Offset(0, -1).Value = ScrollBar3.Value / 2
If Not rngScrlBar1.Offset(0, -1).Value > 0 Then
MsgBox «Please Enter Loan Amount!»
Exit Sub
ElseIf Not rngScrlBar2.Offset(0, -1).Value > 0 Then
MsgBox «Please Enter Annual Interest Rate!»
Exit Sub
ElseIf Not rngScrlBar3.Offset(0, -1).Value > 0 Then
MsgBox «Please Enter Loan Tenure!»
Exit Sub
End If
‘calculate monthly instalment in cell B5:
rngScrlBar3.Offset(1, -1).Value = Pmt((rngScrlBar2.Offset(0, -1).Value / 100) / 12, rngScrlBar3.Offset(0, -1).Value * 12, rngScrlBar1.Offset(0, -1).Value) * -1
End Sub
Example: Form Control SpinButton (Spinner) & Macro to which it is assigned:
Create an Excel Form Control (Spinner) & set Spinner properties — use Shapes.AddFormControl Method to create an Excel Form Control which returns a Shape object representing the new control — Refer Image 9a
Sub FormControl_SpinButton_Shape_Properties()
‘use Shapes.AddFormControl Method to create an Excel Form Control (Spin Button) — this returns a Shape object representing the new control — SpinButton control enables to change (increment or decrement) value in a worksheet range — refer Image 9a.
‘refer Worksheet_Calculate macro — use the Calculate event to trap a sheet recalculation (viz. change in spinner value) so that clicking up / down the scroll arrow moves the active cell content one up / one down, in the worksheet column D
Dim ws As Worksheet, rngSpinBtn As Range, shpSpinBtn As Shape, objSpinBtn As OLEObject
Set ws = Sheets(«Sheet1»)
ws.Activate
‘set range/cell for SpinButton
Set rngSpinBtn = Range(«B2»)
‘delete ActiveX Control SpinButton objects
For Each objSpinBtn In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objSpinBtn.Object) = «SpinButton» Then objSpinBtn.Delete
Next objSpinBtn
‘delete Form Control SpinButton objects
For Each shpSpinBtn In ActiveSheet.Shapes
If shpSpinBtn.Type = msoFormControl Then
If shpSpinBtn.FormControlType = xlSpinner Then shpSpinBtn.Delete
End If
Next shpSpinBtn
rngSpinBtn.ColumnWidth = 3
rngSpinBtn.RowHeight = 24
‘for an already existing Form Control shape — SpinButton, with the name «Spinner 1»
‘Set shpSpinBtn = ws.Shapes(«Spinner 1»)
‘set object variable to the newly added SpinButton Form control — position & size the Spin Button with the cell assigned to the rngSpinBtn variable
‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):
‘a scroll bar gets oriented (horizontal or vertical) based on its size on the worksheet, whereas an ActiveX SpinButton has an Orientation property which can be set to be Auto, Horizontal, or Vertical
Set shpSpinBtn = ws.Shapes.AddFormControl(xlSpinner, Left:=rngSpinBtn.Left, Top:=rngSpinBtn.Top, Width:=rngSpinBtn.Width, Height:=rngSpinBtn.Height)
With shpSpinBtn
‘set a String value as object’s name
.Name = «Spinner 1«
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
‘shape will retain its original proportions when it is resized
.LockAspectRatio = msoTrue
‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).
.AlternativeText = «Spin«
‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.
With .ControlFormat
.Enabled = True
‘spinner will be printed when the document is printed
.PrintObject = True
‘LinkedCell Property specifies a cell to set or store the Value property ie. the current value corresponding to the position of the spinner — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.
.linkedCell = rngSpinBtn.Address
‘specify the minimum and maximum acceptable values (as integer) of the SpinButton control (for the Value property setting)
.Min = 1
.Max = 100
‘SmallChange Property specifies the incremental change, as an integer value, that occurs when a user clicks the scroll arrow. Default value is 1.
.SmallChange = 1
‘Value property sets the control’s current value, which is an integer between maximum & minimum values specified in the Max and Min properties
.Value = 10
End With
End With
End Sub
Macro associated with the Calculate event of the Spinner: this Event-handler procedure must be located in the code module of the object worksheet containing the control (Spinner 1)
Private Sub Worksheet_Calculate()
‘Worksheet.Change Event is triggered when cells on the worksheet are changed by the user or by an external link — use the Calculate event to trap a sheet recalculation (viz. change in spinner value) — clicking up / down the scroll arrow moves the active cell content one up / one down, in the worksheet column D
Application.EnableEvents = False
On Error GoTo ErrorHandler
‘if active cell is not in column D, then exit procedure
If Application.Intersect(ActiveCell, Range(«D:D»)) Is Nothing Then GoTo ErrorHandler
Static PrevValue As Variant
Dim rng As Range
Dim strSpinDir As String
Dim str1 As String, str2 As String
Set rng = ActiveCell
If Shapes(«Spinner 1»).ControlFormat.Value < PrevValue Then
MsgBox «SpinDown»
str1 = rng.Value
str2 = rng.Offset(1, 0)
rng.Value = str2
rng.Offset(1, 0) = str1
rng.Offset(1, 0).Select
ElseIf Shapes(«Spinner 1»).ControlFormat.Value > PrevValue Then
‘if active cell is D1, then exit procedure
If Not Application.Intersect(ActiveCell, Range(«D1»)) Is Nothing Then
Shapes(«Spinner 1»).ControlFormat.Value = 10
PrevValue = Shapes(«Spinner 1»).ControlFormat.Value
GoTo ErrorHandler
End If
MsgBox «SpinUp»
str1 = rng.Value
str2 = rng.Offset(-1, 0)
rng.Value = str2
rng.Offset(-1, 0) = str1
rng.Offset(-1, 0).Select
End If
‘set spin button value, in variance from its Min or Max
Shapes(«Spinner 1»).ControlFormat.Value = 10
PrevValue = Shapes(«Spinner 1»).ControlFormat.Value
Application.EnableEvents = True
ErrorHandler:
Application.EnableEvents = True
End Sub
Example: ActiveX Control SpinButton & Macros associated with the events of the SpinDown & SpinUp ie. clicking down / up the scroll arrow:
Add a new OLEObject to a sheet — ActiveX control (SpinButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 9b
Sub ActiveXControl_SpinButton_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (SpinButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 9b
‘refer event handler procedures of SpinButton1_SpinDown & SpinButton1_SpinUp, associated with the events of the SpinDown & SpinUp ie. clicking down / up the scroll arrow.
Dim ws As Worksheet, rngSpinBtn As Range
‘OLEObject is not used for Form Controls
Dim objSpinBtn As OLEObject
Set ws = Sheets(«Sheet1»)
ws.Activate
‘set range/cell for SpinButton
Set rngSpinBtn = Range(«B2»)
‘delete ActiveX Control SpinButton objects
For Each objSpinBtn In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objSpinBtn.Object) = «SpinButton» Then objSpinBtn.Delete
Next objSpinBtn
rngSpinBtn.ColumnWidth = 3
rngSpinBtn.RowHeight = 24
‘for an already existing ActiveX control SpinButton, with the name «SpinButton1»
‘Set objSpinBtn = ws.OLEObjects(«SpinButton1»)
‘set object variable to the newly added SpinButton ActiveX control — position & size the SpinButton with the cell assigned to the rngSpinBtn variable
Set objSpinBtn = ws.OLEObjects.Add(ClassType:=»Forms.SpinButton.1«, DisplayAsIcon:=False, Left:=rngSpinBtn.Left, Top:=rngSpinBtn.Top, Width:=rngSpinBtn.Width, Height:=rngSpinBtn.Height)
With objSpinBtn
‘set a String value as object’s name
.Name = «SpinButton1«
‘no shadow
.Shadow = False
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
.Enabled = True
‘SpinButton will be printed when the document is printed
.PrintObject = True
‘LinkedCell Property specifies a cell to set or store the Value property — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.
‘set no linked cell
.linkedCell = ««
‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object
‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object
With .Object
‘specify the minimum and maximum acceptable values (as integer) of the SpinButton control (for the Value property setting)
.Min = 1
.Max = 100
‘Orientation Property determines a vertical SpinButton or a horizontal SpinButton. It has 3 settings: (i) fmOrientationAuto (Value -1, default) — SpinButton dimensions automatically determine whether the SpinButton is Vertical or Horizontal. Where width is more than height, SpinButton is Horizontal and where height is more than width, SpinButton is Vertical; (ii) FmOrientationVertical (Value 0) — vertical SpinButton; and (iii) FmOrientationHorizontal (Value 1) — horizontal SpinButton.
.Orientation = fmOrientationVertical
‘SmallChange Property specifies the incremental change, as an integer value, that occurs when a user clicks the scroll arrow. Default value is 1.
.SmallChange = 1
‘Value property sets the control’s current value, which is an integer between maximum & minimum values specified in the Max and Min properties
.Value = 1
‘specify type of mouse pointer
.MousePointer = fmMousePointerArrow
‘set background color to yellow
.BackColor = RGB(255, 255, 0)
‘set scroll arrow color to red
.ForeColor = RGB(255, 0, 0)
End With
End With
End Sub
Macro associated with the event of SpinDown ie. clicking down the scroll arrow of SpinButton1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (SpinButton1)
Private Sub SpinButton1_SpinDown()
‘clicking down the scroll arrow moves the active cell content one down in the worksheet column D
On Error Resume Next
‘if active cell is not in column D, then exit procedure
If Application.Intersect(ActiveCell, Range(«D:D»)) Is Nothing Then Exit Sub
‘spin button value remains constant
SpinButton1.Value = 1
Dim rng As Range, str1 As String, str2 As String
Set rng = ActiveCell
str1 = rng.Value
str2 = rng.Offset(1, 0)
rng.Value = str2
rng.Offset(1, 0) = str1
rng.Offset(1, 0).Select
End Sub
Macro associated with the event of SpinUp ie. clicking up the scroll arrow of SpinButton1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (SpinButton1)
Private Sub SpinButton1_SpinUp()
‘clicking up the scroll arrow moves the active cell content one up in the worksheet column D
On Error Resume Next
‘if active cell is not in column D, then exit procedure
If Application.Intersect(ActiveCell, Range(«D:D»)) Is Nothing Then Exit Sub
‘if active cell is D1, then exit procedure
If Not Application.Intersect(ActiveCell, Range(«D1»)) Is Nothing Then Exit Sub
‘spin button value remains constant
SpinButton1.Value = 1
Dim rng As Range, str1 As String, str2 As String
Set rng = ActiveCell
str1 = rng.Value
str2 = rng.Offset(-1, 0)
rng.Value = str2
rng.Offset(-1, 0) = str1
rng.Offset(-1, 0).Select
End Sub
TextBox — ActiveX Control
A TextBox is a rectangular box, wherein you may type, edit or view text or data, or it may also be a static text field displaying read-only information. Below we illustrate an ActiveX Control TextBox & Macro associated with the GotFocus event of the TextBox.
Example: ActiveX Control TextBox & Macro associated with the GotFocus event of the TextBox:
Add a new OLEObject to a sheet — ActiveX control (TextBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 10a
Sub ActiveXControl_TextBox_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (TextBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 10a
Dim ws As Worksheet, rng As Range
‘OLEObject is not used for Form Controls
Dim objTB As OLEObject
Set ws = Sheets(«Sheet1»)
ws.Activate
Set rng = ws.Range(«A11»)
‘delete ActiveX Control ScrollBar objects
For Each objTB In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objTB.Object) = «TextBox» Then objTB.Delete
Next objTB
‘for an already existing ActiveX control checkbox, with the name «TextBox1»
‘Set objTB = ws.OLEObjects(«TextBox1»)
‘set object variable to the newly added check box ActiveX control — position the check box with the cell assigned to the rng variable
Set objTB = ws.OLEObjects.Add(ClassType:=»Forms.TextBox.1«, DisplayAsIcon:=False, Left:=rng.Left, Top:=rng.Top, Width:=150, Height:=40)
With objTB
‘set a String value as object’s name
.Name = «TextBox1«
‘set shadow
.Shadow = False
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
‘Enabled Property of a TextBox should be set to False if you do not want to allow the user to type directly into the TextBox which should be filled only per the user-selected option, say from a ListBox
.Enabled = True
‘TextBox will be printed when the document is printed
.PrintObject = True
‘the text or value in the TextBox will get stored in this worksheet cell
.linkedCell = rng.Offset(-2, 0).Address
‘wrt to the cell which is under the upper-left corner of the textbox
MsgBox .TopLeftCell.Address
‘wrt to the cell which is under the lower-right corner of the textbox
MsgBox .BottomRightCell.Address
‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object
‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object
With .Object
‘enabling the DragBehavior property enables the drag-and-drop feature for TextBox — dragging in text box starts a drag-and-drop operation on the selected text
.DragBehavior = fmDragBehaviorEnabled
‘EnterKeyBehavior Property: A Boolean value (True/False) which determines the effect when a user presses the ENTER key in a TextBox. If MultiLine property is set to True, then the True value indicates creating a new line on pressing ENTER while the False value (Default) moves focus to the next control in the tab order. If MultiLine property is set to False, then focus is always moved to the next control in the tab order ignoring the EnterKeyBehavior Property.
.EnterKeyBehavior = True
‘if MultiLine is True, set TabKeyBehavior property to True whereby pressing ENTER inserts a Tab and set to False (default) whereby pressing ENTER moves the focus to the next object in the tab order; If MultiLine is False, pressing ENTER will always move the focus to the next control in the tab order.
.TabKeyBehavior = True
‘set SelectionMargin property to True: selection margin occupies a thin strip along the left edge of the control’s edit region, & set to False for the entire edit region to store text.
.SelectionMargin = False
.MultiLine = True
‘caption text will wrap to the next line
.WordWrap = True
‘AutoSize setting for TextBox: (i) if the TextBox is single-line, AutoSize resizes width of TextBox to the length of the text; (ii) if the TextBox is MultiLine with no text, AutoSize resizes width to display single letter (of widest width of that font size) and resizes height to display the entire text; and (iii) if the TextBox is MultiLine with text present, AutoSize does not change the width of the TextBox and resizes height to display the entire text.
.AutoSize = False
‘ScrollBars Property: Specifies whether a TextBox has vertical and/or horizontal scroll bars, or none. There are 4 self-explanatory settings: (i) fmScrollBarsNone (value 0) — default; (ii) fmScrollBarsHorizontal (value 1); (iii) fmScrollBarsVertical (value 2); and (iv) fmScrollBarsBoth (value 3). The scroll bar setting fmScrollBarsNone displays no scroll bar. If AutoSize is set to True, no scroll bar is diplayed because the TextBox enlarges itself to accommodate the additional text or data. If WordWrap is set to True, a multiline TexBox displays no horizontal scroll bar. The scroll bar settings fmScrollBarsHorizontal or fmScrollBarsBoth, display a horizontal scroll bar in a singleline TextBox if the text is longer than the edit region. The scroll bar settings fmScrollBarsVertical or fmScrollBarsBoth, display a vertical scroll bar in a multiline TextBox if the text is longer than the edit region and WordWrap is set to True. To display a horizontal scroll bar in a multiline TexBox, the scroll bar setting should be fmScrollBarsHorizontal, WordWrap should be set to False and the text should be longer than the edit region. Note 1: A horizontal (or vertical) scroll bar is visible only if the control has enough room to include the scroll bar under (or at the right edge of) its edit region.
.ScrollBars = 2
‘text alignment set to center
.TextAlign = fmTextAlignCenter
‘specify characters displayed in TextBox instead of the characters actually entered
‘.PasswordChar = «*«
‘MaxLength property specifies the maximum number of characters which can be entered by the user in a TextBox — set maximum length for password field
‘.MaxLength = 5
‘use the Text property to set text in a TextBox — a value assigned to the Text property gets automatically assigned to the Value property, and vice-versa.
.Text = «Hello»
‘determines how the control visually appears
.SpecialEffect = fmButtonEffectFlat
‘specify type of mouse pointer
.MousePointer = fmMousePointerArrow
‘set the background color for control to yellow
.BackColor = RGB(255, 255, 0)
‘set font color to red
.ForeColor = RGB(255, 0, 0)
‘set background to be Opaque or Transparent — BackStyle property should be set to fmBackStyleOpaque for the BackColor to have any effect
.BackStyle = fmBackStyleOpaque
‘set border
.BorderStyle = fmBorderStyleSingle
.BorderColor = vbBlue
With .Font
.Name = «Arial«
.Bold = True
.Size = 10
.Italic = False
.Underline = False
End With
End With
End With
End Sub
Macro associated with the GotFocus event of the TextBox: this Event-handler procedure must be located in the code module of the object worksheet containing the control (TextBox1) — refer Image 10b.
Private Sub TextBox1_GotFocus()
‘if the active cell is in the worksheet column A (except cell A1), then focus on the TextBox (ex. selecting the TextBox) will set text in the TextBox — refer Image 10b (selecting Jack in column A & then selecting TextBox)
On Error Resume Next
‘if active cell is not in column A, then exit procedure
If Application.Intersect(ActiveCell, Range(«A:A»)) Is Nothing Then Exit Sub
‘if active cell is A1, then exit procedure
If Not Application.Intersect(ActiveCell, Range(«A1»)) Is Nothing Then Exit Sub
If ActiveCell.Value <> «» Then
TextBox1.Text = ActiveCell.Value & «‘s height is » & ActiveCell.Offset(0, 1).Value & » cms & weight is » & ActiveCell.Offset(0, 2).Value & » kg»
End If
End Sub
Label — Form Control or ActiveX Control
Label stores text which is not editable by user, and is used to describe other controls (often a TextBox) or purpose of a worksheet cell or to provide instructions — you may display any descriptive text like caption, title or pictures in a Label.
Below we illustrate: (i) a Form Control Label; and (ii) an ActiveX Control Label.
Example: Form Control Label:
Create an Excel Form Control (Label) & set its properties — use Shapes.AddFormControl Method to create an Excel Form Control which returns a Shape object representing the new control
Sub FormControl_Label_Shape_Properties()
‘use Shapes.AddFormControl Method to create an Excel Form Control (Label) — this returns a Shape object representing the new control
Dim ws As Worksheet, rngLbl As Range, shpLbl As Shape, objLbl As OLEObject
Set ws = Sheets(«Sheet1»)
ws.Activate
‘set range/cell for Label
Set rngLbl = Range(«E15»)
‘delete ActiveX Control Label objects
For Each objLbl In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objLbl.Object) = «Label» Then objLbl.Delete
Next objLbl
‘delete Form Control Label objects
For Each shpLbl In ActiveSheet.Shapes
If shpLbl.Type = msoFormControl Then
If shpLbl.FormControlType = xlLabel Then shpLbl.Delete
End If
Next shpLbl
rngLbl.ColumnWidth = 10
rngLbl.RowHeight = 18
‘for an already existing Form Control Label, with the name «Label 1»
‘Set shpLbl = ws.Shapes(«Label 1»)
‘set object variable to the newly added Label Form control — position & size the Label with the cell assigned to the rngSpinBtn variable
‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):
Set shpLbl = ws.Shapes.AddFormControl(xlLabel, Left:=rngLbl.Left, Top:=rngLbl.Top, Width:=rngLbl.Width, Height:=rngLbl.Height)
With shpLbl
‘set a String value as object’s name
.Name = «Label 1«
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
‘shape will retain its original proportions when it is resized
.LockAspectRatio = msoTrue
‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).
.AlternativeText = «Label1«
‘use the Caption property to display text
.OLEFormat.Object.Caption = «Country«
‘alternatively:
‘TextFrame Property returns a TextFrame object which contains the alignment & anchoring properties for a shape — valid for only a shape having a text frame
.TextFrame.Characters.Text = «USA«
‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.
With .ControlFormat
.Enabled = True
‘label will be printed when the document is printed
.PrintObject = True
End With
End With
End Sub
Example: ActiveX Control Label:
Add a new OLEObject to a sheet — ActiveX control (Label) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 11.
Sub ActiveXControl_Label_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (Label) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 11
‘Label stores text which is not editable by user, and is used to describe other controls — in the Image, Labels are in Green color & describe OptionButtons to their right.
Dim ws As Worksheet, rng As Range
‘OLEObject is not used for Form Controls
Dim objLbl As OLEObject
Set ws = Sheets(«Sheet11»)
ws.Activate
Set rng = Union(Range(«A5»), Range(«A6»))
‘delete ActiveX Control Label objects
For Each objLbl In ActiveSheet.OLEObjects
‘TypeName Function returns the data-type about a variable — TypeName(varname)
If TypeName(objLbl.Object) = «Label» Then objLbl.Delete
Next objLbl
‘for an already existing ActiveX control Label, with the name «Label1»
‘Set objLbl = ws.OLEObjects(«Label1»)
‘set object variable to the newly added Label ActiveX control — position the Label with the cell assigned to the rng variable
Set objLbl = ws.OLEObjects.Add(ClassType:=»Forms.Label.1″, DisplayAsIcon:=False, Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height)
With objLbl
‘set a String value as object’s name
.Name = «Label1«
.Shadow = True
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
.Locked = True
.Enabled = True
‘label will be printed when the document is printed
.PrintObject = True
‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object
‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object
With .Object
‘text alignment (horizontal) set to center — note there is no specific property to vertically align text within a label
.TextAlign = fmTextAlignCenter
‘use the Caption property to display text
.Caption = «Europe«
‘determines how the control visually appears
.SpecialEffect = fmButtonEffectFlat
‘specify type of mouse pointer
.MousePointer = fmMousePointerArrow
‘caption text will wrap to the next line
.WordWrap = True
‘setting AutoSize to True automatically resizes the Caption while False (Default option) keeps the caption size constant wherein content exceeding the control area gets cut.
.AutoSize = False
‘set the background color for control to green
.BackColor = RGB(0, 255, 0)
‘set font color to black
.ForeColor = RGB(0, 0, 0)
‘set background to be Opaque or Transparent — BackStyle property should be set to fmBackStyleOpaque for the BackColor to have any effect
.BackStyle = fmBackStyleOpaque
‘set border
.BorderStyle = fmBorderStyleSingle
‘set border color
.BorderColor = vbBlue
With .Font
.Name = «Arial«
.Bold = True
.Size = 8
.Italic = False
.Underline = False
End With
End With
End With
‘copy Label1 to clipboard
ws.OLEObjects(«Label1»).Copy
‘paste a copy of the Label in the same sheet
ws.Paste
‘position new Label
Selection.Left = Range(«A2»).Left
Selection.Top = Range(«A2»).Top
Selection.Name = «Label2»
ws.OLEObjects(«Label2»).Object.Caption = «America«
End Sub
Illustrating Auto Shapes, Add a connector
Example: Illustrating Auto Shapes, add a connector — refer Image 12 — use the Shapes.AddShape Method to Add a new AutoShape — this returns a Shape object that representing the new AutoShape
Sub AutoShapes_Shape_Properties()
‘illustrating Auto Shapes, add a connector — refer Image 12
‘Use the Shapes.AddShape Method to Add a new AutoShape — this returns a Shape object that representing the new AutoShape — Syntax: Shapes.AddShape(Type, Left, Top, Width, Height). The Type argument specifies the shape type per the MsoAutoShapeType Enumeration
Dim ws As Worksheet
Dim shp As Shape, shpRectangle As Shape, shpTriangle As Shape, shpOval As Shape, shpRightArrow As Shape, shpConn As Shape
Dim rngRectangle As Range, rngTriangle As Range, rngOval As Range, rngRightArrow As Range
Set ws = Sheets(«Sheet1»)
‘———————————
‘delete all auto shapes
For Each shp In ws.Shapes
If shp.Type = msoAutoShape Then
‘MsgBox shp.Name & «, » & shp.AutoShapeType
shp.Delete
End If
Next
‘———————————
‘add 4 shapes in worksheet — Rectangle, Triangle, Oval & Right Arrow:
‘set range/cell for ToggleButton
Set rngRectangle = Range(«B3»)
Set rngTriangle = rngRectangle.Offset(2, 0)
Set rngOval = rngRectangle.Offset(4, 0)
Set rngRightArrow = rngRectangle.Offset(6, 0)
‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property
rngRectangle.ColumnWidth = 18
‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.
rngRectangle.RowHeight = 24
rngTriangle.RowHeight = 36
rngOval.RowHeight = 55
rngRightArrow.RowHeight = 18
‘for an already existing ActiveX control ToggleButton, with the name «ToggleButton1»
‘Set shpRectangle = ws.shapes(«Rectangle 1»)
‘set object variable to the newly added ToggleButton ActiveX control — position & size the Rectangle with the cell assigned to the rngRectangle variable
Set shpRectangle = ws.Shapes.AddShape(Type:=msoShapeRectangle, Left:=rngRectangle.Left, Top:=rngRectangle.Top, Width:=rngRectangle.Width, Height:=rngRectangle.Height)
shpRectangle.Name = «Rectangle 1«
Set shpTriangle = ws.Shapes.AddShape(Type:=msoShapeIsoscelesTriangle, Left:=rngTriangle.Left, Top:=rngTriangle.Top, Width:=rngTriangle.Width, Height:=rngTriangle.Height)
shpTriangle.Name = «Triangle 1«
Set shpOval = ws.Shapes.AddShape(Type:=msoShapeOval, Left:=rngOval.Left, Top:=rngOval.Top, Width:=rngOval.Width, Height:=rngOval.Height)
shpOval.Name = «Oval 1«
Set shpRightArrow = ws.Shapes.AddShape(Type:=msoShapeRightArrow, Left:=rngRightArrow.Left, Top:=rngRightArrow.Top, Width:=30, Height:=rngRightArrow.Height)
shpRightArrow.Name = «Right Arrow 1«
‘refer Shapes collection ie. Shapes object
‘returns 4 (there are four shapes in the collection)
MsgBox ws.Shapes.Count
‘———————————
‘set some common properties for all shapes
‘refer each Shape object
For Each shp In ws.Shapes
‘shape will retain its original proportions when it is resized
shp.LockAspectRatio = msoTrue
‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)
shp.Placement = xlFreeFloating
‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected
shp.Locked = True
‘MsgBox shp.Name
‘shape will be printed when the document is printed
shp.OLEFormat.Object.PrintObject = True
Next shp
‘———————————
‘set properties for Rectangle shape
With shpRectangle
‘indicates the ThreeDFormat object is visible
.ThreeD.Visible = msoTrue
‘use the BevelTopType Property of the ThreeDFormat object to set the type of top bevel, as per the constants defined in MsoBevelType Enumeration: msoBevelCircle, msoBevelSlope, msoBevelSoftRound, msoBevelConvex, …
.ThreeD.BevelTopType = msoBevelCircle
‘set the width & height of the bevel using the BevelTopInset & BevelTopWidth values respectively — this means setting the width & height of the raised edge at the top of a shape
‘set width to 10 points
.ThreeD.BevelTopInset = 10
‘set height to 5 points
.ThreeD.BevelTopDepth = 5
‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).
.AlternativeText = .Name
‘set fill / interior
With .Fill
.Visible = msoTrue
.Solid
‘.ForeColor.SchemeColor = 13
.ForeColor.RGB = RGB(255, 255, 0)
.Transparency = 0
End With
‘set border
With .Line
‘.Weight = 1
.DashStyle = msoLineSolid
.Style = msoLineSingle
.Transparency = 0
‘.ForeColor.SchemeColor = 10
.ForeColor.RGB = RGB(0, 255, 0)
End With
‘set text
With .TextFrame
‘.HorizontalAlignment = xlHAlignCenter
.HorizontalAlignment = xlHAlignLeft
‘.VerticalAlignment = xlVAlignDistributed
.VerticalAlignment = xlVAlignCenter
.Characters.Text = «Rectangle«
With .Characters.Font
.Name = «Arial«
.ColorIndex = 5
.Size = 11
.Bold = True
.Italic = False
End With
.Characters(Start:=1, Length:=1).Font.ColorIndex = 3
End With
End With
‘———————————
‘set properties for Triangle shape
With shpTriangle
‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).
‘shpTriangle.Name is «Triangle 1»
.AlternativeText = .Name
‘set fill / interior
With .Fill
.Visible = msoTrue
‘yellow
.ForeColor.SchemeColor = 13
.Transparency = 0.2
End With
‘set border
With .Line
‘to not display border, use msoFalse
.Visible = msoTrue
.Weight = 1
.DashStyle = msoLineDash
.Transparency = 0
.ForeColor.SchemeColor = 10
End With
‘set text to display caption — first 8 letters of shpTriangle.Name
.OLEFormat.Object.Caption = Left(shpTriangle.Name,
With .OLEFormat.Object.Font
.Name = «Arial«
.Bold = True
.Size = 8
.Italic = False
.ColorIndex = 5
End With
.OLEFormat.Object.Shadow = True
With .Shadow
‘use the Style Property of the ShadowFormat object to set the type of shadowing effect, as per the style constants defined in the MsoShadowStyle Enumeration
.Style = msoShadowStyleOuterShadow
‘use the ForeColor Property of the ShadowFormat object to set the fill color for the shadow
.ForeColor.RGB = RGB(255, 0, 0)
.Blur = 2
‘use the Size Property of the ShadowFormat object to set a value representing the percentage size for the shadow
.Size = 90
‘the OffsetX Property of the ShadowFormat object sets a value, in points, indicating the horizontal offset of the shadow to the chart area, with a negative value offsetting the shadow to the left
.OffsetX = 6
‘the OffsetY Property of the ShadowFormat object sets a value, in points, indicating the vertical offset of the shadow to the chart area, with a negative value offsetting the shadow to the above
.OffsetY = -5
‘the Transparency Property of the ShadowFormat object sets the degree of the transparency in a fill, as a value from 0.0 (opaque) to 1.0 (clear), for solid color fills
.Transparency = 0.2
End With
End With
‘———————————
‘Oval shape: set an image to the specified fill
With shpOval.Fill
‘using the ChartFillFormat.UserPicture Method to fill the shape with an image — specify filename & path of image file
.UserPicture «C:UsersamitDocumentsPhotosDollar.jpg»
End With
‘———————————
‘Right Arrow shape:
With shpRightArrow
.Fill.ForeColor.RGB = RGB(0, 0, 255)
.ThreeD.BevelTopType = msoBevelConvex
‘to not display border, use msoFalse
.Line.Visible = msoFalse
‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on shpRightArrow will execute the NextStep macro
.OnAction = «NextStep«
End With
‘———————————
‘add the connector in 5 steps:
‘To add a connector: 1) Add a connector shape; 2) specify the shape it begins at; 3) specify the shape it ends at; 4) reroute the connector given the position of the 2 shapes which it links; 5) format the connector;
‘use the Shapes.AddConnector Method to create a connector — this method returns a Shape object representing the new connector. Syntax: Shapes.AddConnector(Type, BeginX, BeginY, EndX, EndY) — use the Type argument to specify the connectr type (msoConnectorCurve, msoConnectorElbow, msoConnectorStraight). The BeginX & EndX arguments specify the horizontal position (in points) of the start & end points relative to the upper-left corner of the document & the BeginY & EndY arguments specify the vertical position (in points) of the start & end points relative to the upper-left corner of the document. All arguments are necessary to specify.
‘The new connector added does not connect anything — you will need to use the BeginConnect & EndConnect methods to specify shapes where the connector begins & ends at.
‘add the connector (curved connector) without regard to its position or size as it will be redrawn later.
Set shpConn = ws.Shapes.AddConnector(msoConnectorCurve, 1, 1, 1, 1)
Dim iLastSite As Integer
iLastSite = shpOval.ConnectionSiteCount
With shpConn
‘use the ConnectorFormat.BeginConnect Method to attach the beginning of the connector to a shape — Syntax: ConnectorFormat.BeginConnect(ConnectedShape, ConnectionSite) — the ConnectedShape argument specifies the shape to which the beginning of the connector is attached to. The ConnectionSite argument specifies the number (Integer) of the connection site on the shape between 1 and the number of connection sites on a shape (which can be returned by using the Shape.ConnectionSiteCount Property).
‘attach the beginning of the connector to connection site 2 on the shpTriangle & the attach the connector end to the last connection site of the shpOval
.ConnectorFormat.BeginConnect shpTriangle, 2
‘use the ConnectorFormat.EndConnect Method to attach the end of the connector to a shape
.ConnectorFormat.EndConnect shpOval, iLastSite
‘use the ShapeRange.RerouteConnections Method to reroute the connector so as to take the shortest possible path between the shapes it connects, and for this the ends of a connector may be reattached to different connecting sites on the connected shapes.
‘.RerouteConnections
‘format the connector — set color to red & thickness to 2 pts
.Line.ForeColor.RGB = RGB(255, 0, 0)
.Line.Weight = 2
End With
End Sub
Mercenary Пользователь Сообщений: 6 |
Добры день, уважаемые пользователи! Как абсолютный «0» в VBA взываю к вашей помощи. Нужно, что бы при нажатии кнопки появлялось диалоговое окно для выбора файла и далее этот файл должен быть внедрен в ячейку. Он должен быть в виде значка с именем исходного файла. Файл должен быть любым (картинка, звук, документ ворд, эксель или pdf) Заранее спасибо! |
Sanja Пользователь Сообщений: 14838 |
#2 13.10.2015 13:34:36 Что-то типа этого?
Изменено: Sanja — 13.10.2015 13:38:20 Согласие есть продукт при полном непротивлении сторон. |
||
Mercenary Пользователь Сообщений: 6 |
#3 13.10.2015 14:54:57 Спасибо, но не до конца работает.
что то нужно добавить… |
||
The_Prist Пользователь Сообщений: 14181 Профессиональная разработка приложений для MS Office |
#4 13.10.2015 17:27:03
Так надо как-то просвещаться: Диалоговое окно выбора файлов/папки
Что-то непонятно. Код добавили для отображения иконкой, а отображаться должно имя файла…Что надо, куда и как? Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||||||
Mercenary Пользователь Сообщений: 6 |
#5 13.10.2015 21:10:33 Огромное спасибо!
И при нажатии Отмена все равно вылетает ошибка 1004 |
||
vikttur Пользователь Сообщений: 47199 |
Mercenary, для оформления кода в сообщении — кнопка <…> |
The_Prist Пользователь Сообщений: 14181 Профессиональная разработка приложений для MS Office |
#7 13.10.2015 21:58:35
А что-то в приведенном коде нет обработки нажатия Отмена. В то время как в статье, на которую я дал ссылку в каждом коде есть обработка нажатия Отмены. Мало того — строки этой обработки помечены комментариями.
Насколько знаю за сам тип значка отвечает IconFileName, а не IconLabel. И содержаться там должен путь до библиотеки значков. При вставке стандартными средствами Excel извлекает его из файлов своих библиотек. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||||
Mercenary Пользователь Сообщений: 6 |
Все дело в том, что я неделю назад первый раз увидел макрос и мой уровень в этом ниже плинтуса. поэтому мне сложно разобраться. Все равно не выходит как нужно. Нужно как: Нужно, что бы макрос работал точно так же, как если я нажимаю: Вставка/Объект/из файла (в виде значка). |
The_Prist Пользователь Сообщений: 14181 Профессиональная разработка приложений для MS Office |
#9 14.10.2015 12:31:00
Мы разные макрорекордеры, видимо, используем:
Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||||
Mercenary Пользователь Сообщений: 6 |
#10 14.10.2015 15:42:26 Разобрался более менее) Спасибо! А про макрорекодеры, я использую встроенный в эксель)) есть другие?)) просто он не пишет нажатия на кнопки в верхней панели самого экселя.. Осталось неясно, как прописать значение искомой иконки для варианта с выбором «All Files». Если в код просто не прописывать IconFileName, то по каким то непонятным причинам, даже с условием DisplayAsIcon:=True фалы вставляются либо некорректно, либо в виде белого большого прямоугольника.
И вдогонку второй вопрос: Изменено: Mercenary — 14.10.2015 15:43:40 |
||
The_Prist Пользователь Сообщений: 14181 Профессиональная разработка приложений для MS Office |
Если иконку брать неоткуда — как там может быть подпись вообще? Тут надо либо указывать все параметры для Icon, либо будут глюки. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
Mercenary Пользователь Сообщений: 6 |
Код как раз в предыдущем сообщении. Значение true в конце строки («All files(*.*),*.*», 1, «Выбрать файлы», , True) дает возможность вставлять несколько файлов одновременно. Это первый вариант. Второй — если я просто вставил один, потом нажал еще раз и вставил второй файл. |
The_Prist Пользователь Сообщений: 14181 Профессиональная разработка приложений для MS Office |
При первом варианте надо делать цикл по выбранным файлам и вставлять по очереди. Сдвигая параметр Left каждого на ширину предыдущего. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
Thender Пользователь Сообщений: 4 |
может кто знает как вставить в таблицу картинку как в проводнике когда выбран вид папки огромные значки? , получится эдакая миниатюра. |
vikttur Пользователь Сообщений: 47199 |
#15 21.09.2016 14:35:58 Может, Вы ознакомились с правилами и знаете, что для отдельного вопроса нужно создавать отдельную тему? |
- Remove From My Forums
-
Question
-
Dear All,
I am using the following VBA code to embed PDF (non-linked) into an Excel file
ActiveSheet.OLEObjects.Add(Filename:=FilePath, Link:=False, DisplayAsIcon:=True, IconFileName:=»C:Windowssystem32packager.dll»,
IconIndex:=0, IconLabel:=IconName).SelectIn our office everybody is using O365 so the EXCEL version we are using is the same (I checked). BUT still there are 3 different outcomes
for the above mentioned VBA code:a) Embedded file appears and the appearing name of the icon is the string defined as IconName
b) Embedded file appears, but there is no icon, a differen Logo appears and the appearing name of the embedded file is a temporary name
given by the system like 6DC40FF5.pdfc) Run-time error 1004 massage appears and the macro stops
How is it possible that the same VBA coded (using the same Excel versions) results in 3 different outcomes?
Any idea for solution?
Thanks a lot
Peter
-
Moved by
Wednesday, September 9, 2015 1:20 AM
-
Moved by
Answers
-
Hi Peter,
Based on the code abolve, it should dispaly the new OLE object either as an icon or as its regular picture.
>>b) Embedded file appears, but there is no icon, a differen Logo appears and the appearing name of the embedded file is a temporary name given by the system like 6DC40FF5.pdf<<
The issue is relative to the icon file instead of Office. Did you same operating system on the different computer? And I suggest that you check icon file to see whether it exits and to ensure the dll contain same icon.
>>c) Run-time error 1004 massage appears and the macro stops<<
The 1004 run-time error messages mean application-defined or object-defined error. This message is displayed when an error generated with the
Raise method or Error statement doesn’t correspond to an error defined by Visual Basic for Applications. It is also returned by the
Error function for
arguments that don’t correspond to errors defined by Visual Basic for Applications. Thus it may be an error you defined, or one that is defined by an object, including
host applications like Microsoft Excel, Visual Basic, and so on.Please ensure that you can insert the file manually when you get this error message. So that it can also works for the macro. You can get more detail about this error from link below:
Application-defined or object-defined errorRegards & Fei
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey.-
Proposed as answer by
Fei XueMicrosoft employee
Friday, September 11, 2015 9:47 AM -
Marked as answer by
Fei XueMicrosoft employee
Monday, September 14, 2015 8:24 AM
-
Proposed as answer by
В этом разделе описываются конкретные сведения об использовании элементов управления ActiveX в листы и листы диаграмм.Общие сведения о добавлении и работа с элементами управления просмотрите С помощью элементов управления ActiveX в документе и Создание настраиваемого диалогового окна.
При работе с элементами управления на листах необходимо помните следующее:
- Помимо
стандартных свойств, доступных для элементов управления ActiveX, можно
использовать следующие свойства с помощью элементов управления ActiveX в
Microsoft Excel: BottomRightCell, LinkedCell, ListFillRange, Размещение, Печать объекта, TopLeftCellи ZOrder.
Эти свойства можно задать и возвращаются в имени элемента управления ActiveX.Следующий пример прокрутка окна книги, поэтому CommandButton1 находится в левом верхнем углу.
Set t = Sheet1.CommandButton1.TopLeftCell
With ActiveWindow
.ScrollRow = t.Row
.ScrollColumn = t.Column
End With
- При активации элемента управления ActiveX отключены некоторые свойства и методы Microsoft Excel Visual Basic.Например метод сортировки
не может использоваться, когда элемент управления активен, поэтому
следующие возникает ошибка кода кнопки в процедуре события click (так
как элемент управления остаются активными при нажатии его).
Private Sub CommandButton1.Click
Range(«a1:a10»).Sort Key1:=Range(«a1»)
End Sub
You can work around this problem by activating some other element on the sheet before you use the property or method that failed. For example, the following code sorts the range:
Private Sub CommandButton1.Click
Range(«a1»).Activate
Range(«a1:a10»).Sort Key1:=Range(«a1»)
CommandButton1.Activate
End Sub
-
Элементы
управления на книги Microsoft Excel, внедренные в документ в другом
приложении не будут работать при двойном щелчке рабочей книги для ее
редактирования.Элементы управления будет работать, если пользователь щелкает правой кнопкой мыши книгу и выбирает команду Открыть контекстное меню. -
При сохранении книги Microsoft Excel в формате книги Microsoft Excel 5.0/95 теряются данные элемента управления ActiveX.
-
Ключевое слово Me в процедуре события для элемента управления ActiveX на листе ссылается на лист, не к элементу управления.
Добавление элементов управления с помощью Visual Basic
В Microsoft Excel элементы управления ActiveX, представлены OLEObject объектов в коллекции OLEObjects (все объекты OLEObject также находятся в коллекции фигур ).Для программного добавления элемента управления ActiveX в лист, используйте метод Add коллекции OLEObjects .В следующем примере добавляется кнопка команды на листе 1.
Worksheets(1).OLEObjects.Add «Forms.CommandButton.1», _
Left:=10, Top:=10, Height:=20, Width:=100
С помощью свойства элемента управления с помощью Visual Basic
Чаще всего кода Visual Basic будет ссылаться на элементы управления ActiveX с именем.В следующем примере изменяется заголовок элемента управления с именем «CommandButton1».
Sheet1.CommandButton1.Caption = «Run»
Обратите
внимание, что при использовании имя элемента управления за пределами
модуль класса для таблицы, содержащей элемент управления, необходимо
указать имя элемента управления, с помощью имя листа.
Чтобы
изменить имя элемента управления, используемого в коде Visual Basic,
выберите элемент управления и в окне Свойства задайте для свойства (имя) .
Так как элементы управления ActiveX также представлены OLEObject объектов в коллекции OLEObjects , можно задать с помощью объектов в коллекции свойств элемента управления.В следующем примере задается положение левого края элемента управления с именем «CommandButton1».
Worksheets(1).OLEObjects(«CommandButton1»).Left = 10
Возвращает объект фактического элемента управления, с помощью свойства объекта можно задать свойства элемента управления, которые не отображаются в виде свойства объекта OLEObject .В следующем примере задается заголовок для CommandButton1.
Worksheets(1).OLEObjects(«CommandButton1»). _
Object.Caption = «run me»
Так как все объекты OLE, также входят в коллекции фигур , коллекции можно использовать для настройки свойств для нескольких элементов управления.Следующий пример выравнивание левого края все элементы управления на листе 1.
For Each s In Worksheets(1).Shapes
If s.Type = msoOLEControlObject Then s.Left = 10
Next
Имена элементов управления с помощью фигур и OLEObjects семейств сайтов
Элемент управления ActiveX на листе имеет два имени: имя, который содержит элемент управления, который можно просмотреть в поле имя при просмотре листа и имя кода для элемента управления, который можно просматривать в ячейке справа от (имя) в свойств фигуры окно ES.При первом добавлении элемента управления в лист, соответствующие имени фигуры и с кодовым именем.Тем не менее если изменить код имени или имени фигуры, другой не изменяется автоматически в соответствии с.
Использование кода имя элемента управления в именах его процедур обработки событий.Тем не менее при вернуть элемент управления из коллекции фигур или OLEObjects для листа, необходимо использовать имя фигуры, а не имя кода, для ссылки на элемент управления по имени.Например предположим, что флажок Добавить в лист и наличия CheckBox1 фигуры имя по умолчанию и имя кода по умолчанию.Нажмите, чтобы изменить имя элемента управления кода с помощью следующей команды chkFinished рядом с пунктом (имя)
в окне Свойства, необходимо использовать chkFinished в процедуру имен
событий, но по-прежнему необходимо использовать CheckBox1 возвращает
элемент управления из фигур или ** OLEObject** семейства сайтов, как показано в следующем примере.
Private Sub chkFinished_Click()
ActiveSheet.OLEObjects(«CheckBox1»).Object.Value = 1
End Sub