Excel vba checkbox in listbox

В этой статье мы рассмотрим такой элемент управления в окне ToolBox, как Флажок, за работу с ним отвечает класс VBA CheckBox. Флажки довольно часто используются на формах, их часто называют “птичками” или “галочками”. Сами по себе объекты vba класса CheckBox являются независимыми друг от друга, и позволяют определить одно из двух состояний: галочка установлена, или галочка снята.

Флажки удобны при составлении опросов, например, из десяти цветов нужно отметить те, которые больше всего нравятся. Собственно, в этой статье мы и попытаемся сделать своеобразный опрос, но пока, давайте рассмотрим основные свойства класса CheckBox:

Name – ну, как всегда, имя объекта

Caption – определяет надпись, которая будет находится возле галочки справа.

TripleState – свойство позволяет определить третье состояние флажка. Как упоминалось выше, компонент vba CheckBox может принимать два значения: галочка установлена (true), галочка снята (false), но можно задать и третье состояние (Null) – в этом случае объект будет серого цвета и будет недоступен. Если это свойство содержит значение false – будут поддерживаться только два состояния, если true – все три.

Value – данное свойство позволяет получить состояние выбора (true, false или Null).

Событие Change класса CheckBox происходит при изменении состояния флажка.

Скажу честно, цель статьи – показать простой пример использования Флажков, поэтому я особо не вникал во все премудрости данного компонента.

И так, цель задания: добавить в проект форму, на ней разместить 12 флажков, разделенных на 4 группы по 3 штуки, Например,

  • Телефон: Nokia, Samsung, Siemens
  • Девушка: рыжая, светлая, темная (Ха-ха!!!!)
  • Ноутбук: Asus, Acer, Lenovo
  • Транспорт: велосипед, автомобиль, самокат

Ну, думаю, вы суть поняли: размещаете надпись, а под ней в столбик флажки. Справа я добавил компонент ListBox – как только мы будем ставить галочку для vba CheckBox, элемент сразу будет добавляться в список, плюс, элемент управлении Флажок сразу будет становится недоступным после выбора (свойство Enabled примет значение False). Еще на форме (UserForm) нам понадобится кнопка, которая будет очищать список, и будет делать доступными все флажки.

Знаю, знаю, пример не столько практичен, сколько теоретичен….

excel vba checkbox

В коде для формы нужно добавить следующие процедуры:

Private Sub CheckBox1_Change()
    If CheckBox1.Value = True Then
        ListBox1.AddItem CheckBox1.Caption
        CheckBox1.Enabled = False
    End If
End Sub
 
Private Sub CheckBox2_Change()
    If CheckBox2.Value = True Then
        ListBox1.AddItem CheckBox2.Caption
        CheckBox2.Enabled = False
    End If
End Sub
 
Private Sub CheckBox3_Change()
    If CheckBox3.Value = True Then
        ListBox1.AddItem CheckBox3.Caption
        CheckBox3.Enabled = False
    End If
End Sub
 
Private Sub CheckBox4_Change()
    If CheckBox4.Value = True Then
        ListBox1.AddItem CheckBox4.Caption
        CheckBox4.Enabled = False
    End If
End Sub
 
Private Sub CheckBox5_Change()
    If CheckBox5.Value = True Then
        ListBox1.AddItem CheckBox5.Caption
        CheckBox5.Enabled = False
    End If
End Sub
 
Private Sub CheckBox6_Change()
    If CheckBox6.Value = True Then
        ListBox1.AddItem CheckBox6.Caption
        CheckBox6.Enabled = False
    End If
End Sub
Private Sub CheckBox7_Change()
    If CheckBox7.Value = True Then
        ListBox1.AddItem CheckBox7.Caption
        CheckBox7.Enabled = False
    End If
End Sub
 
Private Sub CheckBox8_Change()
    If CheckBox8.Value = True Then
        ListBox1.AddItem CheckBox8.Caption
        CheckBox8.Enabled = False
    End If
End Sub
 
Private Sub CheckBox9_Change()
    If CheckBox9.Value = True Then
        ListBox1.AddItem CheckBox9.Caption
        CheckBox9.Enabled = False
    End If
End Sub
 
Private Sub CheckBox10_Change()
    If CheckBox10.Value = True Then
        ListBox1.AddItem CheckBox10.Caption
        CheckBox10.Enabled = False
    End If
End Sub
 
Private Sub CheckBox11_Change()
    If CheckBox11.Value = True Then
        ListBox1.AddItem CheckBox11.Caption
        CheckBox11.Enabled = False
    End If
End Sub
 
Private Sub CheckBox12_Change()
    If CheckBox12.Value = True Then
        ListBox1.AddItem CheckBox12.Caption
        CheckBox12.Enabled = False
    End If
End Sub
 
Private Sub CommandButton1_Click()
    CheckBox1.Enabled = True
    CheckBox2.Enabled = True
    CheckBox3.Enabled = True
    CheckBox4.Enabled = True
    CheckBox5.Enabled = True
    CheckBox6.Enabled = True
    CheckBox7.Enabled = True
    CheckBox8.Enabled = True
    CheckBox9.Enabled = True
    CheckBox10.Enabled = True
    CheckBox11.Enabled = True
    CheckBox12.Enabled = True
    ListBox1.Clear
End Sub

Процедуры от CheckBox1_Change до CheckBox12_Change носят практически один и тот же характер – идет обработка события Change. Если состояние флажка ровно true (вы поставили птичку), то в список ListBox1 с помощью метода AddItem добавляется значение, хранимое в свойстве Caption (надпись рядом с птичкой). Далее происходит присваивание значения False свойству Enabled – делаем объект CheckBox недоступным.

Процедура CommandButton1_Click отвечает за обработку клика по кнопке. Видим, что для каждого флажка свойство Enabled принимает значение True, то есть, он становится доступным. Метод Cleare – полностью очищает список ListBox1.

И так, в этой статье мы кратко рассмотрели работу с классом CheckBox (Флажок) vba языка, да, я рассмотрел довольно простой пример использования, но… не все сразу.

Кстати, пример показанный в статье можно использовать и в Exel и в Word. Сам расчет идет на то, что бы описать базовую информацию по языку VBA, а уже потом переходить к чему-то более сложному. Так, как только я закончу с элементами управления, я перейду к описанию синтаксиса языка VBA, который практически идентичен языку VBScript, но код VBScript может выполняться самостоятельно в теле отдельного файла (сценариях), а VBA – работает в теле документа Microsoft.

UserForm Controls — ComboBox and ListBox

———————————————————-

Contents:

Difference between ListBox and ComboBox

Key Properties of ComboBox and ListBox

Add Items/Data to (Populate) a ListBox or ComboBox

Extract ListBox & ComboBox Items, with VBA

Delete ListBox rows using the RemoveItem Method

———————————————————-

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. Using ActiveX Controls on a Worksheet have been illustrated in detail, in the separate section of «Excel VBA: ActiveX Controls, Form Controls & AutoShapes on a Worksheet».

An Excel VBA ListBox or ComboBox 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.

Difference between ListBox and ComboBox:

1. The ComboBox 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 ListBox shows a certain number of values with or without a scroll bar. In a ComboBox, only one row of items is visible at a given time (without using the drop-down) whereas in a ListBox one or more can be visible at a time.

2. In a ComboBox you can select ony one option from the list, while in a ListBox 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 ListBox. In this sense, ComboBox is a combination of TextBox and ListBox.

4. CheckBox can be used within ListBox, but not within ComboBox. ListBox 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). To use CheckBoxes in a ListBox, set ListStyle property (in Properties Window)  to fmListStyleOption (vba code: ListBox1.ListStyle = fmListStyleOption). This setting is best used with a multiselect ListBox.

——————————————————————————————————————-

Key Properties of ComboBox and ListBox

Note1: All properties and methods given below are common to both ListBox and ComboBox, unless mentioned otherwise. Also refer «2. UserForm and Controls — Properties.» for properties common to the UserForm and most Controls.

Note 2: In below given examples, vba codes are required to be entered in the Code Module of the UserForm, unless specified otherwise.  

AddItem Method:

Adds an item to the list, in a single-column ListBox or ComboBox. Adds a row to the list (ie. 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 is an Integer which 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. AddItem method can only be used with a macro or vba code. Note: AddItem method adds an item to the first column in a multi-column ListBox or ComboBox, and to add an item further to the first column, use the List or Column property specifying the item’s row and column number. More than one row can also be added at a time to a ListBox or ComboBox by using the List or Column properties (AddItem adds one row at a time). This means that you can copy a two-dimensional array of values to a ListBox or ComboBox, using List or Column properties rather than adding each individual element using the AddItem method. Note: Using the Column property to copy a two-dimensional array of values to a ListBox or ComboBox, transposes the array contents and equates myArray(iRow, iColumn) to ListBox1.Column(iCol, iRow). List property copies an array without transposing it and myArray(iRow, iColumn) equates to ListBox1.List(iRow, iColumn). Refer Image 13 for example.

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, second column has a value of 2, and so on. Setting the BoundColumn value to 1 will assign the value from column 1 to the ComboBox or ListBox, and so on. BoundColumn property lets the user to store a different set of values per specified column while TextColumn property displays one set of values, viz. use the Text property to return the value from the first column (specified in the TextColumn property) containing the names and the BoundColumn property can specify another column containing height wherein on selecting a particular person’s name in the ListBox, his height will get returned or stored (refer Image 10). The ColumnWidths property of a column can be set to zero to not display it in the ListBox. 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). This setting is useful if you want to determine the row of the selected item in a ComboBox or ListBox. BoundColumn Property can be set in the Properties window and can also be used with a macro or vba code. Note: Where the ControlSource mentions =Sheet3!D2 (vba code: .ControlSource = «=Sheet3!D2»), the value in the BoundColumn of the selected row will get stored in cell D2, Sheet3.

Example 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  (in a Single Selection ListBox) — refer Image 7

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnHeads = True

.ColumnCount = 2

‘ColumnWidths property of the second column is set to zero to not display it in the ListBox.

.ColumnWidths = «50;0»

.RowSource = «=Sheet3!A2:B6»

.MultiSelect = fmMultiSelectSingle

.BoundColumn = 0

End With

End Sub

Private Sub CommandButton1_Click()
‘BoundColumn value is set as 0 which assigns the value of the ListIndex property (which is the number of the selected row) as the value of the control. Note: MultiSelect Property is set to fmMultiSelectSingle which allows only single selection.

If ListBox1.Value <> «» Then

TextBox1.Value = ListBox1.Value + 2

End If

End Sub

Clear Method:

Removes all items in a ComboBox or ListBox. Syntax: Control.Clear. Clear method will not work if ComboBox or ListBox is bound to data, hence RowSource data should be cleared before use. Clear method can only be used with a macro or vba code. 

Column Property:

Refers to a specific column, or column and row combination, in a multiple-column ComboBox or ListBox. Syntax: Control.Column(iColumn, iRow). Column property can only be used with a macro or vba code and is not available at design time. iColumn specifies the column number wherein iColumn = 0 means the first column in the List. iRow specifies the row number wherein iRow = 0 means the first row in the List. Both iColumn and iRow are integer values ranging from 0 to number of columns and rows (respectively) in the list minus 1. 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. You can copy a two-dimensional array of values to a ListBox or ComboBox, using Column (or List) property rather than adding each individual element using the AddItem method. Column property can be used to assign the contents of a ComboBox or ListBox to another control, viz. TextBox (refer Image 8). Note: Using the Column property to copy a two-dimensional array of values to a ListBox or ComboBox, transposes the array contents and equates myArray(iRow, iColumn) to ListBox1.Column(iCol, iRow). List property copies an array without transposing it and myArray(iRow, iColumn) equates to ListBox1.List(iRow, iColumn). Refer Image 13 for example.

Example 2: Load ListBox using AddItem method and List & Column properties; and use Column property to assign the contents of ListBox to TextBox — refer Image 8

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

.RowSource = «=Sheet2!A2:B6»

.MultiSelect = fmMultiSelectMulti

End With

‘clearing the TextBox if it is not empty
TextBox1 = «»

End Sub

Private Sub CommandButton1_Click()
‘Add items in ListBox using AddItem method to add new rows; use List & Column properties to add items in columns beyond the first column; and use Column property to assign the contents of ListBox to TextBox

‘AddItem method will not work if ListBox is bound to data, hence RowSource is cleared if it had been set
ListBox1.RowSource = «»

‘Create a new row with AddItem 

ListBox1.AddItem «banana»
‘add item in second column of this first row, using List property
ListBox1.List(0, 1) = «tuesday»
‘adding items in the 3 columns of the first row — this will become the second row in the end
ListBox1.List(0, 2) = «day 2»

ListBox1.AddItem «orange»

‘add item in second column of this second row, using Column property
ListBox1.Column(1, 1) = «wednesday»
‘adding items in the 3 columns of the second row — this will become the third row in the end
ListBox1.Column(2, 1) = «day 3»

‘Create a new row with AddItem and position as row number 1
ListBox1.AddItem «apple», 0

ListBox1.List(0, 1) = «monday»

‘adding items in the 3 columns and positioning this row as the first row — this will push down the above two rows
ListBox1.List(0, 2) = «day 1»

‘item in column number 3 and row number 2 of ListBox
TextBox1.Value = ListBox1.Column(2, 1)

End Sub

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 property can be set in the Properties window and can also be used with a macro or vba code.

ColumnHeads Property:

A Boolean value (True/False) which determines display of column headings (in a single row) for ComboBox or ListBox. ColumnHeads property can be set in the Properties window and can also be used with a macro or vba code. Column Headings can be displayed only if ColumnHeads is set to True in Properties window (VBA code: ListBox1.ColumnHeads = True) and if you bind the ListBox to a range (ie. set RowSource to a range that includes headings). Note: AddItem method will not work if ListBox or ComboBox is bound to data, hence RowSource property should be cleared for using AddItem.

List Property:

List Property is used in conjunction with the ListCount and ListIndex properties to return items in a ListBox or ComboBox control. Syntax -> Control.List(iRow,iCol). Each item in a list has a row number and a column number, wherein row and column numbers start with zero. iRow specifies the row number wherein iRow = 2 means the third row in the List. iColumn specifies the column number wherein iColumn = 0 means the first column in the List. Omitting to specify the iColumn will retrieve the first column. Specify iColumn only for a multi-column ListBox or ComboBox. List Property can only be used with a macro or vba code and is not available at design time. Note: To copy a two-dimensional array of values to a ListBox or ComboBox, use List or Column properties. To add a one-dimensional array or to add an individual element, use the AddItem method. Items can be removed from a List using the RemoveItem method. List property is available only by using a macro or VBA.

Example 3: Use Selected & List properties to display multiple-selected ListBox items (choose any column to display) in TextBox, and link a worksheet cell with TextBox using ControlSource property — refer Image 9. 

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnHeads = True

.ColumnCount = 2

‘ColumnWidths property of the second column is set to zero to not display it in the ListBox.

.ColumnWidths = «50;0»

.RowSource = «=Sheet3!A2:B6»

.MultiSelect = fmMultiSelectMulti

.TextColumn = 1

End With

With TextBox1

.MultiLine = True

‘the text or value in the TextBox will get stored in the worksheet cell — Sheet3!F2
.ControlSource = «=Sheet3!F2»
‘if the cell Sheet3!F2 contains any text, this will not appear in the TextBox on initialization of UserForm
.Value = «»

End With

End Sub

Private Sub CommandButton1_Click()
‘Use Selected & List properties to display multiple-selected ListBox items (choose any column to display) in TextBox, and link a worksheet cell with TextBox using ControlSource property

TextBox1.Value = «»

‘check all items in a ListBox
For n = 0 To ListBox1.ListCount — 1

‘if a ListBox item is selected, it will display in TextBox
If ListBox1.Selected(n) = True Then

If TextBox1.Value = «» Then

‘ListBox1.List(n, 0) or ListBox1.List(n)displays the first column in TextBox, ListBox1.List(n, 1) displays the second column and so on
‘alternate code which displays the second column in TextBox: TextBox1.Value = Range(ListBox1.RowSource).Offset(n, 1).Resize(1, 1).Value
TextBox1.Value = ListBox1.List(n, 1)

Else

‘alternate code which displays the second column in TextBox: TextBox1.Value = TextBox1.Value & vbCrLf & Range(ListBox1.RowSource).Offset(n, 1).Resize(1, 1).Value

TextBox1.Value = TextBox1.Value & vbCrLf & ListBox1.List(n, 1)

End If

End If

Next n

End Sub

ListCount Property:

Determines the total number of rows in a ListBox or ComboBox. This property can only be used with a macro or vba code and is not available at design time. Note: The column headings row is also counted, if ColumnHeads are displayed. The ListCount property can be used with the ListRows property to specify the number of rows to display in a ComboBox.

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. Hence, it is an integer value ranging from 0 to the total number of items in a ComboBox or ListBox minus 1. ListIndex returns -1 when no rows are selected. This property can only be used with a macro or vba code and is not available at design time. Note: 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. In a Single Selection enabled ListBox (viz. MultiSelect property setting of fmMultiSelectSingle), ListIndex returns the index of the selected item and hence ListIndex property should be used here to return and set a selection.

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). The ListCount property can be used with the ListRows property to specify the number of rows to display in a ComboBox. ListRows property can be set in the Properties window and can also be used with a macro or vba code. ListRows Property is valid for ComboBox and not for ListBox.

Example 4: Using the ListCount property with the ListRows property, to set number of rows to display in ComboBox

Private Sub UserForm_Initialize()
‘this macro sets the ListRow value, on initialization of the UserForm

With ComboBox1

If .ListCount > 5 Then

.ListRows = 5

Else

.ListRows = .ListCount

End If

End With

End Sub

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 property can be set in the Properties window and can also be used with a macro or vba code. Note: MultiSelect Property is valid for ListBox and not for ComboBox. When multiple selections are made (viz. fmMultiSelectMulti or fmMultiSelectExtended), the selected items can be determined only by using the Selected property (Selected property is available by using macro) of the ListBox. The Selected property will have values ranging from 0 to ListCount minus 1 and will be True if the item is selected and False if not selected. The Selected property determines the items you chose, and the List property returns the items.

Example 5: Determining selected item in a Single Selection ListBox, in VBA:

Private Sub CommandButton1_Click()
‘determine and display selected item in a ListBox which allows only a single selection (viz. MultiSelect Property is set to fmMultiSelectSingle)
‘you can also determine selected item in a ListBox which allows only a single selection, by using the Selected Property (as used in a Multiple Selection enabled ListBox)

‘alternatively: If ListBox1.ListIndex >= 0 Then
If ListBox1.Value <> «» Then

MsgBox ListBox1.Value

End If

End Sub

RemoveItem Method:

A specified row is removed from the list in a ComboBox or ListBox. Syntax: Control.RemoveItem(Row_Index). Row_Index is the row number which is specified to be removed, wherein the first row is numbered 0, and so on. RemoveItem method will not work if ComboBox or ListBox is bound to data, hence RowSource data should be cleared before use. RemoveItem method can only be used with a macro or vba code.

RowSource Property:

Specifies the source of a list (which could be a worksheet range in Excel), for a ComboBox or ListBox. RowSource property can be set in the Properties window and can also be used with a macro or vba code. To set RowSource property in Properties window, enter without inverted commas: «=Sheet2!A2:A6» which populates ComboBox or ListBox with values in cells A2:A6 in Sheet2. VBA code for this is: ListBox1.RowSource = «=Sheet2!A2:A6». It is not necessary to use the equal mark in «=Sheet2!A2:A6» while setting the property and ListBox1.RowSource = «Sheet2!A2:A6» will have the same effect.

Selected Property:

Specifies whether an item is selected in a ListBox control. Syntax: Control.Selected(Item_Index). Returns True/False if the item is Selected/NotSelected; Set to True/False to select the item or remove selection [viz. Control.Selected(ItemIndex) = True/False]. Item_Index is an integer value ranging from 0 to number of items in the list minus 1, indicating its relative position in the list, viz. ListBox.Selected(2) = True selects the third item in the list. Selected property is particularly useful when working with multiple selections. Selected Property can only be used with a macro or vba code and is not available at design time. Note1: 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. In a Single Selection enabled ListBox (viz. MultiSelect property setting of fmMultiSelectSingle), ListIndex returns the index of the selected item and hence ListIndex property should be used here to return and set a selection. Note2: Selected Property is valid for ListBox and not for ComboBox.

Example 6: Determining selected items in a multiple-selection enabled ListBox using Selected & List properties:

Private Sub CommandButton1_Click()
‘display all selected items in a ListBox using the Selected property (valid for a ListBox with MultiSelect Property setting of either single-selection or multiple-selection)

‘check all items in a ListBox
For n = 0 To ListBox1.ListCount — 1

‘if a ListBox item is selected, it will display in MsgBox

If ListBox1.Selected(n) = True Then

‘display a selected item
MsgBox ListBox1.List(n)

End If

Next n

End Sub

Style Property:

Valid for ComboBox only, not for ListBox. This property determines choosing or setting the value of ComboBox. There are 2 settings: (i) fmStyleDropDownCombo (value 0). The user has both options of typing a custom value in the text area or select from the drop-down list. This is the default value.; (ii) fmStyleDropDownList (value 2). The user can only select from the drop-down list, like in ListBox. Style Property can be set in the Properties window and can also be used with a macro or vba code.

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 property if the TextColumn property is not set. First column has a TextColumn value of 1, second column has a value of 2, and so on. Setting the TextColumn value to -1 indicates that the first column with a ColumnWidths value greater than 0 will be displayed. 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) viz. use the Text property to return the value from the first column (specified in the TextColumn property) containing the names and the BoundColumn property can specify another column containing height wherein on selecting a particular person’s name in the ListBox, his name & height will be returned. The ColumnWidths property of any column can be set to zero to not display it in the ListBox. Setting the TextColumn value to 0 displays the ListIndex value (which is the number of the selected row) in TextColumn Property — this setting is useful if you want to determine the row of the selected item. TextColumn property can be set in the Properties window and can also be used with a macro or vba code. Note: In a ComboBox, when a user selects an item, the column specified in the TextColumn property will be displayed in the ComboBox’s text box portion.

Example 7: Display first column in the List and use the TextColumn & BoundColumn Properties to return values from first & third columns (in a Single Selection ListBox) — refer Image 10

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnHeads = True

.ColumnCount = 3

‘set the ColumnWidths property of second & third columns to zero to not display them in the ListBox

.ColumnWidths = «40;0:0»

.RowSource = «=Sheet2!A2:C6»

.MultiSelect = fmMultiSelectSingle

‘specifies the column of data in a ListBox that supplies data for its Text property

.TextColumn = 1

.BoundColumn = 3

End With

End Sub

Private Sub CommandButton1_Click()
‘TextColumn value is set as 1 and BoundColumn value is set as 3.

‘works only if MultiSelect Property of ListBox is set to fmMultiSelectSingle which allows single selection.
If ListBox1.Value <> «» Then   

‘use the ListBox Text property to return the value from the column specified in the TextColumn column, whereas the ListBox Value property returns the value from the column specified in the BoundColumn property

TextBox1.Value = ListBox1.Text & » — » & ListBox1.Value & » cms»

End If

End Sub

———————————————————————————————————————  

Add Items/Data to (Populate) a ListBox or ComboBox

1. Setting the RowSource property of a ListBox or ComboBox in a UserForm

VBA code — if the list is static:

Me.ListBox1.RowSource = «Sheet1!A1:B6»

or
Me.ListBox1.RowSource = «=Sheet1!A1:B6»

VBA code — if the list is dynamic:

Me.ListBox1.RowSource = «Sheet1!A1:B» & Sheet1.Cells(Rows.Count, «B»).End(xlUp).Row

Note: You can set the RowSource property of a ListBox or ComboBox in the Properties Window (without using vba code), by entering -> Sheet1!A1:B6

Example 8: Populate ComboBox by setting the RowSource property to a named list — refer Image 11

Private Sub UserForm_Initialize()
‘populate ComboBox by setting the RowSource property to a named list

With ComboBox1

.ColumnCount = 2

.ColumnWidths = «50;50»

.ColumnHeads = True

‘For a named list (viz. “HeightList” in Range A2:B6), the RowSource property can be set to Sheet1!HeightList

.RowSource = «Sheet1!HeightList»

End With

End Sub

2. Populate a ComboBox or ListBox from an Array:

VBA code — populate single column in ListBox:

ListBox1.List = Array(«RowOne», «RowTwo», «RowThree», «RowFour»)

VBA code — populate single column in ComboBox:

ComboBox1.List = Array(«Apples», «Bananas», «Oranges», «Pears»)

VBA code — populate ListBox from array named myArray:

Dim myArray As Variant
myArray = Array(«Adidas», «Nike», «Reebok»)
Me.ListBox1.List = myArray

VBA code — Populate single column ComboBox:

Dim i As Integer
Dim myArray As Variant

myArray = Array(«Adidas», «Nike», «Reebok», «Puma», «Polo»)

    For i = LBound(myArray) To UBound(myArray)

Me.ComboBox1.AddItem myArray(i)

Next

Example 9 — Populate a multi-column Listbox directly with Worksheet Range — multiple rows added at one time using the List property:

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

End With

‘Load Worksheet Range directly to a ListBox

Dim rng As Range

Set rng = Sheet1.Range(«A1:C6»)

Me.ListBox1.List = rng.Cells.Value

End Sub

Example 10 — Populate a multi-column Listbox directly with Worksheet Range — multiple rows added at one time using the List property:

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

End With

‘Load Worksheet Range directly to a ListBox:

Dim var As Variant

var = Sheet1.Range(«A1:C6»)

Me.ListBox1.List = var

End Sub

Example 11: Load Worksheet Range to a multi-column ListBox, after placing Range data in a 2-dimensional Array — refer Image 12

Option Base 1
——————————————
Private Sub UserForm_Initialize()
‘Load Worksheet Range to a ListBox, after placing data in an Array

Dim rng As Range
Dim cell As Range
Dim totalRows As Integer, totalColumns As Integer
Dim iRow As Integer, iCol As Integer
Dim myArray() As Variant

Set rng = Sheet1.Range(«A1:C6»)
totalRows = Sheet1.Range(«A1:C6»).Rows.Count
totalColumns = Sheet1.Range(«A1:C6»).Columns.Count

‘if Option Base 1 was not set, this line of code should be: ReDim myArray(1 To totalRows, 1 To totalColumns)
ReDim myArray(totalRows, totalColumns)

‘place worksheet range data in an Array:
For Each cell In rng

For iRow = 1 To totalRows

For iCol = 1 To totalColumns

myArray(iRow, iCol) = rng.Cells(iRow, iCol)

Next iCol

Next iRow

Next

‘set ListBox properties and load Array to ListBox

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

.List = myArray

End With

End Sub

Example 12: Load a 2-dimensional array to ListBox using the List property (copies an array without transposing it) and Column property (which transposes the contents of the array) — refer Image 13

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

End With

With ListBox2

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

End With

End Sub

Private Sub CommandButton1_Click()
‘create a 2-dimensional array and load to ListBox using the List property (copies an array without transposing it) and Column property (which transposes the contents of the array)

‘Declaring the array and its dimensions. The array has been named myArray, of size 3 by 3 (three rows by three 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.
Dim myArray(3, 3)

‘populate column 1 of myArray, with numbers

For n = 0 To 2

myArray(n, 0) = n + 1

Next n

‘populate column 2 of myArray
myArray(0, 1) = «R1C2»
myArray(1, 1) = «R2C2»
myArray(2, 1) = «R3C2»

‘populate column 3 of myArray
myArray(0, 2) = «R1C3»
myArray(1, 2) = «R2C3»
myArray(2, 2) = «R3C3»

‘copy data to ListBox1 (using List property) and ListBox2 (using Column property):

‘copies an array without transposing it
ListBox1.List() = myArray
‘transposes the contents of the array
ListBox2.Column() = myArray

End Sub

3. Populate a ComboBox or ListBox with AddItem method

Example 13: Populate a single-column ListBox from worksheet range

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 1

.ColumnWidths = «50»

.ColumnHeads = False

‘AddItem method will not work if ListBox is bound to data, hence RowSource is cleared if it had been set

.RowSource = «»

End With

‘populating a single-column ListBox with AddItem method
Dim cell As Range
Dim rng As Range

    
Set rng = Sheet1.Range(«A1:A6»)

For Each cell In rng.Cells

Me.ListBox1.AddItem cell.Value

Next cell

End Sub

Example 14: Populate a single-column ListBox with values from 1 to 500

Private Sub UserForm_Initialize()
‘set ListBox properties on activation of UserForm

With ListBox1

.ColumnCount = 1

.ColumnWidths = «50»

‘AddItem method will not work if ListBox is bound to data, hence RowSource is cleared if it had been set

.RowSource = «»

End With

‘populate a single-column ListBox with values from 1 to 500, and «N/A»
With ListBox1

.AddItem «N/A»

For i = 1 To 500

.AddItem i

Next i

End With

End Sub

Example 15: Create a new row with AddItem and specify its row number — refer Image 14

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 1

.ColumnWidths = «50»

.ColumnHeads = False

‘AddItem method will not work if ListBox is bound to data, hence RowSource is cleared if it had been set

.RowSource = «»

End With

‘using AddItem method to populate single-column ListBox:
ListBox1.AddItem «banana»
ListBox1.AddItem «orange»

‘Create a new row with AddItem and position as row number 1 — this will push down the above two rows
ListBox1.AddItem «apple», 0
‘Create a new row with AddItem and position as row number 2 — this will push down the above two rows to no. 3 and 4
ListBox1.AddItem «pears», 1

End Sub

Example 16: Populate a ComboBox with the 12 months in a year — Refer Image 15

Private Sub UserForm_Initialize()
‘set ComboBox properties on initialization of UserForm

With ComboBox1

.ColumnCount = 1

.ColumnWidths = «50»

.ColumnHeads = False

‘AddItem method will not work if ComboBox is bound to data, hence RowSource is cleared if it had been set

.RowSource = «»

End With

‘populates ComboBox with the 12 months in a year

For n = 1 To 12

ComboBox1.AddItem Format(DateSerial(2011, n, 1), «mmmm»)

Next n

End Sub

4. Populate a multi-column ComboBox or ListBox using AddItem method and List & Column properties

Example 17:  refer Image 16

Private Sub UserForm_Initialize()
‘set ComboBox properties on initialization of UserForm

With ComboBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

‘AddItem method will not work if ComboBox is bound to data, hence RowSource is cleared if it had been set

.RowSource = «»

End With

‘Populating a multi-column ListBox using AddItem method and List & Column properties:

‘Create a new row with Additem
ComboBox1.AddItem «banana»
‘add item in second column of this first row, using List property
ComboBox1.List(0, 1) = «tuesday»
‘adding items in the 3 columns of the first row — this will become the second row in the end
ComboBox1.List(0, 2) = «day 2»

ComboBox1.AddItem «orange»

‘add item in second column of this second row, using Column property
ComboBox1.Column(1, 1) = «wednesday»
‘adding items in the 3 columns of the second row — this will become the third row in the end
ComboBox1.Column(2, 1) = «day 3»

‘Create a new row with Additem and position as row number 1
ComboBox1.AddItem «apple», 0
ComboBox1.List(0, 1) = «monday»

‘adding items in the 3 columns and positioning this row as the first row — this will push down the above two rows
ComboBox1.List(0, 2) = «day 1»

End Sub

5. Populate a multi-column ListBox from a worskheet range, using AddItem method and List property

Example 18:  refer Image 17

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

‘AddItem method will not work if ListBox is bound to data, hence RowSource is cleared if it had been set

.RowSource = «»

End With

End Sub

Private Sub CommandButton1_Click()
‘populate a multi-column ListBox from a worskheet range, using AddItem method and List property

Dim counter As Long
Dim totalRows As Long

‘determine total number of rows in column A
totalRows = Sheet4.Cells(Rows.Count, «A»).End(xlUp).Row
counter = 0

‘ListBox gets populated with all rows in column A:
Do

With Me.ListBox1

counter = counter + 1

‘create a new row with Additem
.AddItem Sheet4.Cells(counter, 1).Value
‘add item in second column of a row
.List(.ListCount — 1, 1) = Sheet4.Cells(counter, 1).Offset(0, 1).Value
‘add item in third column of a row

.List(.ListCount — 1, 2) = Sheet4.Cells(counter, 1).Offset(0, 2).Value

End With

Loop Until counter = totalRows

End Sub

6. Add a new item/row to the list if ComboBox is bound to data in a worksheet. 

Example 19: refer Images 18a & 18b

Private Sub UserForm_Initialize()
‘set ComboBox properties on initialization of UserForm

With ComboBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = True

.BoundColumn = 1

‘a named-range (name: «cbRange») has been created in Sheet3 of the workbook, using the Name Manager: «=Sheet3!$A$2:$C$6»

.RowSource = «cbRange»

End With

End Sub

Private Sub CommandButton1_Click()
‘add a new item/row to the list if ComboBox is bound to data in a worksheet

Dim colNo As Long

‘determine first column of the named-range «cbRange»
colNo = Range(«cbRange»).Column

‘create a new single-column named-range (name: «cbRangeTemp»), populated with only the first column of the named-range «cbRange».
Range(«cbRange»).Resize(Range(«cbRange»).Rows.Count, 1).Name = «cbRangeTemp»

‘checks if ComboBox1.Value is already existing in column 1 of named-range «cbRange»
If Application.CountIf(Range(«cbRangeTemp»), ComboBox1.Value) = 0 Then

‘resizing the named-range «cbRange», to add another worksheet row at the end, wherein the ComboBox1.Value will get posted:

Range(«cbRange»).Resize(Range(«cbRange»).Rows.Count + 1).Name = «cbRange»

ComboBox1.RowSource = «cbRange»

‘posting columns of the new row with values from ComboBox1, TextBox1 & TextBox2:

Sheet3.Cells(Range(«cbRange»).Rows.Count + 1, colNo) = ComboBox1.Value

Sheet3.Cells(Range(«cbRange»).Rows.Count + 1, colNo).Offset(0, 1) = TextBox1.Text

Sheet3.Cells(Range(«cbRange»).Rows.Count + 1, colNo).Offset(0, 2) = TextBox2.Text

Else

MsgBox «Item already in List»

End If

ComboBox1.Value = «»
TextBox1.Text = «»
TextBox2.Text = «»

End Sub

——————————————————————————————————————————————-  

Extract ListBox & ComboBox Items, with VBA

VBA code — Display selected ComboBox item in TextBox:

‘the text area of ComboBox shows the item entered by user of his own choice or that selected from list items, and this item gets displayed in TextBox

TextBox1.Value = ComboBox1.Value

Note: VBA code-> TextBox1.Value = ListBox1.Value, or TextBox1.Text = ListBox1.Value, will work only in case MultiSelect property of ListBox is set to fmMultiSelectSingle, ie. in case of a single-selection enabled ListBox. It will copy the selected item (value in BoundColumn) from the list.

VBA code — Copy selected ComboBox item to a worksheet range:

‘the text area of ComboBox shows the item entered by user of his own choice or that selected from list items, and this item is copied to the worksheet range

Sheet1.Range(«G4»).Value = ComboBox1.Value

Note: VBA code-> Sheet4.Range(«G4»).Value = ListBox1.Value, will work only in case MultiSelect property of ListBox is set to fmMultiSelectSingle, ie. in case of a single-selection enabled ListBox. It will copy the selected item (value in BoundColumn) from the list.

VBA code — Copy ComboBox item determined by its position, to a worksheet range:

‘an existing ComboBox item, determined by its position (row 4, column 1), posted to a worksheet cell

Sheet1.Range(«F2»).Value = ComboBox1.List(3, 0)

Note: VBA code for ListBox -> Sheet1.Range(«F2»).Value = ListBox1.List(3, 0)

Example 20: Extracting ListBox items (of multi-column ListBox) to a worksheet range — refer Image 19

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = True

.RowSource = «Sheet2!A2:C6»

.MultiSelect = fmMultiSelectMulti

End With

End Sub

Private Sub CommandButton1_Click()
‘Use Selected & List properties to copy multiple-selected ListBox items (of multi-column ListBox) to a worksheet range

‘check all items/rows in a ListBox
For r = 0 To ListBox1.ListCount — 1

‘if a ListBox row is selected, it will get copied to the worksheet range

If ListBox1.Selected(r) = True Then

‘copying multi-column ListBox rows to corresponding/matching worksheet rows & columns:

For c = 1 To ListBox1.ColumnCount

Sheet1.Cells(r + 1, c).Value = ListBox1.List(r, c — 1)

Next c

End If

Next r

End Sub

Example 21: Extract multiple items in a row from a single-selection enabled & multi-column ListBox, and copy to worksheet range — refer Image 20

Private Sub UserForm_Initialize()
‘set ListBoxBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = True

.BoundColumn = 1

.MultiSelect = fmMultiSelectSingle

.RowSource = «Sheet3!A2:C6»

End With

End Sub

Private Sub CommandButton1_Click()
‘extract multiple items in a row from a single-selection enabled & multi-column ListBox, and copy to worksheet range
‘ListIndex property is used to return and set a selection in a single-selection ListBox, but not in a multi-selection ListBox
‘ListBox1.Value will work only in case of a single-selection ListBox. It will copy the selected item (value in BoundColumn) from the list.

Dim rng As Range
Set rng = Sheet3.Cells(9, 1)

    
If ListBox1.Value <> «» Then

rng.Value = ListBox1.Value

rng.Offset(0, 1).Value = ListBox1.List(ListBox1.ListIndex, 1)

rng.Offset(0, 2).Value = ListBox1.List(ListBox1.ListIndex, 2)

End If

    
End Sub

Example 22: Select or enter name in ComboBox, and lookup its corresponding Grade in a worksheet range — refer Image 21

Private Sub UserForm_Initialize()
‘set comboBox properties on initialization of UserForm

With ComboBox1

.ColumnCount = 1

.ColumnWidths = «50»

.ColumnHeads = True

.RowSource = «Sheet3!A2:B6»

End With

‘disallow manual entry in TextBox

With TextBox1

.Enabled = False

End With

End Sub

Private Sub CommandButton1_Click()
‘select or enter name in ComboBox, and lookup its corresponding Grade in a worksheet range — use ComboBox, TextBox & CheckBox properties and worksheet functions Vlookup and Countif

Dim totalRows As Long

‘determine total number of rows in column B
totalRows = Sheet3.Cells(Rows.Count, «B»).End(xlUp).Row

Me.ComboBox1.ControlTipText = «Select Name»
Me.CommandButton1.ControlTipText = «Click to get Grade»

‘Name selected in ComboBox is posted to TextBox
TextBox1.Text = ComboBox1.Value

‘Grade will be searched only if a name is selected and the CheckBox is selected:
If CheckBox1 = True And TextBox1.Text <> «» Then

‘check if name selected or entered in ComboBox is present in the lookup range:

If Application.CountIf(Sheet3.Range(«A1:A» & totalRows), TextBox1.Text) > 0 Then

‘lookup Grade of selected Name, in the worksheet range

Sheet3.Cells(1, 4).Value = TextBox1.Text & «‘s grade is » & Application.VLookup(TextBox1.Text, Sheet3.Range(«A1:B» & totalRows), 2, False)

Else

MsgBox «Name not found!»

End If

End If

End Sub

——————————————————————————————————————————————-  

Delete ListBox rows using the RemoveItem Method

Example 23: Use RemoveItem method to delete a ListBox row. The below code deletes the row from the ListBox and also deletes the row items (or rows) in the worksheet — refer Images 22a and 22b.

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

.MultiSelect = fmMultiSelectMulti

End With

Dim totalRows As Long

‘determine total number of rows in column A
totalRows = Sheet3.Cells(Rows.Count, «A»).End(xlUp).Row

‘load a dynamic worksheet range to a ListBox
Dim rng As Range
Set rng = Sheet3.Range(«A2:C» & totalRows)
Me.ListBox1.List = rng.Cells.Value

‘removes all items in ListBox
‘ListBox1.Clear

End Sub

Private Sub CommandButton1_Click()
‘use RemoveItem method to delete a ListBox row. The below code deletes the row from the ListBox and also deletes the row items (or rows) in the worksheet

Dim n As Long, i As Long
Dim var As Variant

‘deleting row from ListBox using RemoveItem method:

‘check all items in a ListBox; reverse order (Step -1) is used because rows are being deleted from ListBox.
For n = ListBox1.ListCount — 1 To 0 Step -1

If ListBox1.Selected(n) = True Then

‘item to be deleted is stored in the variable named var

var = ListBox1.List(n, 0)
ListBox1.RemoveItem (n)

‘determine row number in which items are to be deleted; Note: value of variable named var is derived from first column, hence Range(«A:A») is searched in the Match formula.
i = Application.Match(var, Sheet3.Range(«A:A»), 0)

‘delete all 3 columns of the determined row in the worksheet:
Sheet3.Cells(i, 1) = «»

Sheet3.Cells(i, 1).Offset(0, 1) = «»
Sheet3.Cells(i, 1).Offset(0, 2) = «»

‘use this code instead of the preceding 3-lines, to delete the determined row in the worksheet
‘Sheet3.Rows(i).Delete

End If

Next n

End Sub

Example 24: Delete all rows in ListBox, using RemoveItem method

Private Sub UserForm_Initialize()
‘set ListBoxBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.BoundColumn = 1

.MultiSelect = fmMultiSelectMulti

‘RemoveItem method will not work if ListBox is bound to data, hence RowSource is cleared if it had been set

ListBox1.RowSource = «»

End With

For n = 2 To 6

With Me.ListBox1

‘create a new row with Additem

.AddItem Sheet3.Cells(n, 1).Value
‘add item in second column of a row

.List(.ListCount — 1, 1) = Sheet3.Cells(n, 1).Offset(0, 1).Value
‘add item in third column of a row

.List(.ListCount — 1, 2) = Sheet3.Cells(n, 1).Offset(0, 2).Value

End With

Next n

End Sub

Private Sub CommandButton1_Click()
‘delete all rows in ListBox, using RemoveItem method

Dim n As Integer

For n = 1 To ListBox1.ListCount

‘Note: «ListBox1.RemoveItem 0» is the same as «ListBox1.RemoveItem (0)»

‘alternate code: ListBox1.RemoveItem 0

ListBox1.RemoveItem ListBox1.ListCount — 1

Next n

End Sub

Skip to content

Using CheckBox To Select All Items Of ListBox

Sometimes it is necessary to select all items of the Excel Listbox. The codes shown below can be used to select all items of the listbox on the userform with checkbox :

excel search in listbox

The codes that we used :

Private Sub CheckBox1_Click()

Dim r As Long

If CheckBox1.Value = True Then

ListBox2.MultiSelect = fmMultiSelectMulti

    For r = 0 To ListBox2.ListCount – 1

        ListBox2.Selected(r) = True

    Next r

   Else

   For r = 0 To ListBox2.ListCount – 1

        ListBox2.Selected(r) = False

   Next r

   End If

End Sub

📥 Read More & Download Template 

Multiple List Box Selections in Excel VBA

📥 Read More and Download Template

Элемент управления CheckBox

Флажки (пользователи часто называют их “галками” или “птичками”) и кнопки с фиксацией используются для выбора невзаимоисключающих вариантов (если этих вариантов немного).

 

рис . 1.1 Элемент управления Checkbox на панели ToolBox

рис. 1.2 Элемент управления Checkbox на форме

рис. 1.3 Пример элемента управления Checkbox на форме

Флажки удобны при составлении опросов, например, из десяти цветов нужно отметить те, которые больше всего нравятся. Собственно, в этой статье мы и попытаемся сделать своеобразный опрос, но пока, давайте рассмотрим основные свойства класса CheckBox:

Name – имя объекта

Caption – определяет надпись, которая будет находится возле галочки справа.

TripleState – свойство позволяет определить третье состояние флажка. Как упоминалось выше, компонент vba CheckBox может принимать два значения: галочка установлена (true), галочка снята (false), но можно задать и третье состояние (Null) – в этом случае объект будет серого цвета и будет недоступен. Если это свойство содержит значение false – будут поддерживаться только два состояния, если true – все три.

Value – данное свойство позволяет получить состояние выбора (true, false или Null).

Событие Change класса CheckBox происходит при изменении состояния флажка.

И так, цель задания: добавить в проект форму, на ней разместить 12 флажков, разделенных на 4 группы по 3 штуки, Например,

  • Телефон: Nokia, Samsung,      Siemens
  • Девушка: рыжая, светлая,      темная (для примера)
  • Ноутбук: Asus, Acer, Lenovo
  • Транспорт: велосипед,      автомобиль, самокат

Ниже приведен пример формы:

Справа добавлен компонент ListBox – как только мы будем ставить галочку для vba CheckBox, элемент сразу будет добавляться в список, плюс, элемент управлении Флажок сразу будет становится недоступным после выбора (свойство Enabled примет значение False). Еще на форме (UserForm) нам понадобится кнопка, которая будет очищать список, и будет делать доступными все флажки.

В коде для формы нужно добавить следующие процедуры:

Private Sub CheckBox1_Change()

If CheckBox1.Value = True Then

ListBox1.AddItem CheckBox1.Caption

CheckBox1.Enabled = False

End If

End Sub

Private Sub CheckBox2_Change()

If CheckBox2.Value = True Then

ListBox1.AddItem CheckBox2.Caption

CheckBox2.Enabled = False

End If

End Sub

Private Sub CheckBox3_Change()

If CheckBox3.Value = True Then

ListBox1.AddItem CheckBox3.Caption

CheckBox3.Enabled = False

End If

End Sub

Private Sub CheckBox4_Change()

If CheckBox4.Value = True Then

ListBox1.AddItem CheckBox4.Caption

CheckBox4.Enabled = False

End If

End Sub

Private Sub CheckBox5_Change()

If CheckBox5.Value = True Then

ListBox1.AddItem CheckBox5.Caption

CheckBox5.Enabled = False

End If

End Sub

Private Sub CheckBox6_Change()

If CheckBox6.Value = True Then

ListBox1.AddItem CheckBox6.Caption

CheckBox6.Enabled = False

End If

End Sub

Private Sub CheckBox7_Change()

If CheckBox7.Value = True Then

ListBox1.AddItem CheckBox7.Caption

CheckBox7.Enabled = False

End If

End Sub

Private Sub CheckBox8_Change()

If CheckBox8.Value = True Then

ListBox1.AddItem CheckBox8.Caption

CheckBox8.Enabled = False

End If

End Sub

Private Sub CheckBox9_Change()

If CheckBox9.Value = True Then

ListBox1.AddItem CheckBox9.Caption

CheckBox9.Enabled = False

End If

End Sub

Private Sub CheckBox10_Change()

If CheckBox10.Value = True Then

ListBox1.AddItem CheckBox10.Caption

CheckBox10.Enabled = False

End If

End Sub

Private Sub CheckBox11_Change()

If CheckBox11.Value = True Then

ListBox1.AddItem CheckBox11.Caption

CheckBox11.Enabled = False

End If

End Sub

Private Sub CheckBox12_Change()

CheckBox12.Value = True Then

ListBox1.AddItem CheckBox12.Caption

CheckBox12.Enabled = False

End If

End Sub

Private Sub CommandButton1_Click()

CheckBox1.Enabled = True     CheckBox2.Enabled = True     CheckBox3.Enabled = True     CheckBox4.Enabled = True     CheckBox5.Enabled = True     CheckBox6.Enabled = True     CheckBox7.Enabled = True     CheckBox8.Enabled = True     CheckBox9.Enabled = True     CheckBox10.Enabled = True     CheckBox11.Enabled = True     CheckBox12.Enabled = True     ListBox1.Clear

End Sub

Процедуры от CheckBox1_Change до CheckBox12_Change носят практически один и тот же характер – идет обработка события Change. Если состояние флажка ровно true (вы поставили птичку), то в список ListBox1 с помощью метода AddItem добавляется значение, хранимое в свойстве Caption (надпись рядом с птичкой). Далее происходит присваивание значения False свойству Enabled – делаем объект CheckBox недоступным.

Процедура CommandButton1_Click отвечает за обработку клика по кнопке. Видим, что для каждого флажка свойство Enabled принимает значение True, то есть, он становится доступным. Метод Cleare – полностью очищает список ListBox1.

  • Home
  • VBForums
  • Visual Basic
  • Office Development
  • [RESOLVED] HELP dynamic listbox with checkbox column on VBA form

  1. Sep 12th, 2008, 12:40 PM


    #1

    Rikki_UW is offline

    Thread Starter


    Addicted Member


    Resolved [RESOLVED] HELP dynamic listbox with checkbox column on VBA form

    Hey all, last coop semester I got a lot of help programing a website in vb.net, this semester I have been given the minor task of creating a form in Excel. The general idea is that if a user double clicks (or something) on certain cells in the main worksheet it will open up a form with two sections. At the moment I am designing the GUI of the first section. The purpose is to display a list of problems and their appropriate solutions with checkboxes beside each, so that for whichever ones are checked the problems are added to the cell on separate rows and the solution to the adjacent cell on the appropriate row. I have another sheet as the source of the information by putting =Sheet1!$B$2:$C$3 (I have yet to filter the appropriate lines) under the RowSource property of a listbox. It has the two columns, but I cannot find any information on adding a checkbox column. I can’t even find any decent Microsoft resources.

    If someone could help me figure out how to do this, or at least point me to a decent Excel VBA resource, I would greatly appreciate it.

    Thanks,

    —Rikki


  2. Sep 12th, 2008, 01:17 PM


    #2

    Re: HELP dynamic listbox with checkbox column on VBA form

    There is no checked listbox in Excel VBA. You sould just use the selection as a designation for «checked».

    VB/Office Guru� (AKA: Gangsta Yoda)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum. Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru� Word SpellChecker�.NETVB/Office Guru� Word SpellChecker� VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24″ LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6


  3. Sep 12th, 2008, 01:29 PM


    #3

    Re: HELP dynamic listbox with checkbox column on VBA form

    I would suggest using an Excel Userform for your project.

    If you add a ListBox to the Userform and set theListStyle property to 1 — frmListStyleOption then set the MultiSelect property to 1 — fmMultiSelectMulti you will have a listbox which checkboxes.


  4. Sep 12th, 2008, 01:38 PM


    #4

    Rikki_UW is offline

    Thread Starter


    Addicted Member


    Re: HELP dynamic listbox with checkbox column on VBA form

    aha! That is exactly what I wanted, thank you so much.

    Do you know of any good resources? I’ve never done this before and am not sure how to implement most of the other stuff, like having the Userform come up when the cell is double clicked, and filtering the listbox with appropriate data using a hidden ID column, and putting the lines selected in the appropriate cells and resizing the cell to fit, the list goes on…

    Thanks,
    —Rikki


  5. Sep 12th, 2008, 01:41 PM


    #5

    Re: HELP dynamic listbox with checkbox column on VBA form

    Cells don’t have click events.

    You gave a general idea, what are the specification program specs that you have?


  6. Sep 12th, 2008, 02:00 PM


    #6

    Rikki_UW is offline

    Thread Starter


    Addicted Member


    Re: HELP dynamic listbox with checkbox column on VBA form

    There is nothing specific, my employer just explained to me what he wanted and drew a diagram of the userform. I want a way for users to be able to simply open the userform and have it populated with appropriate options. I am adding it to a workbook created by someone else, who has a macro or something so that in specific cells there is a tiny drop down arrow beside it when it is highlighted and has options to put in the cell (yes, no, N/A). Maybe something like that, but a button to open the form instead of an arrow?

    The first part of the userform will have options for that specific row, and the second has two text boxes, so that when OK is clicked the info in the textboxes is appended to two cells (both a series of merged cells) and the checked items from the first part are neatly placed in the appropriate cells. The problem/comment goes in one cell and the solution (if there is one) goes in the adjacent cell. The tricky part is that any number of problems/comments would be in the same cell so the cell has to resize itself automatically and the problems and solutions have to be on the correct line of their appropriate cells.

    Last edited by Rikki_UW; Sep 12th, 2008 at 02:05 PM.


  7. Sep 13th, 2008, 12:39 PM


    #7

    Re: HELP dynamic listbox with checkbox column on VBA form

    Quote Originally Posted by Hack

    I would suggest using an Excel Userform for your project.

    If you add a ListBox to the Userform and set theListStyle property to 1 — frmListStyleOption then set the MultiSelect property to 1 — fmMultiSelectMulti you will have a listbox which checkboxes.

    Yea thats what I was saying about using the listboxes selection property for a checked duplication but it doesnt have to be on a userform. You can draw a listbox on the sheet itself if one so desires.

    VB/Office Guru� (AKA: Gangsta Yoda)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum. Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru� Word SpellChecker�.NETVB/Office Guru� Word SpellChecker� VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24″ LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6


  8. Sep 15th, 2008, 03:13 AM


    #8

    Re: HELP dynamic listbox with checkbox column on VBA form

    Quote Originally Posted by Rikki_UW

    aha! That is exactly what I wanted, thank you so much.

    Do you know of any good resources? I’ve never done this before and am not sure how to implement most of the other stuff, like having the Userform come up when the cell is double clicked, and filtering the listbox with appropriate data using a hidden ID column, and putting the lines selected in the appropriate cells and resizing the cell to fit, the list goes on…

    Thanks,
    —Rikki

    Hi for a double click event you can use this. Just an example

    Code:

    Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
        MsgBox "aaa"
    End Sub

    What you want to achieve is not difficult at all…

    What do you have till now?

    Last edited by Siddharth Rout; Sep 15th, 2008 at 03:29 AM.

    A good exercise for the Heart is to bend down and help another up…
    Please Mark your Thread «Resolved», if the query is solved

    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27″ 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero


  9. Sep 15th, 2008, 07:16 AM


    #9

    Rikki_UW is offline

    Thread Starter


    Addicted Member


    Re: HELP dynamic listbox with checkbox column on VBA form

    I have made the actual userform but done very little coding, here is what I have so far:

    Code:

    Private Sub UserForm1_Initialize()
    Call FindEntries
    End Sub
    
    Private Sub UserForm1_Activate()
    Call FindEntries
    End Sub
    
    Private Sub FindEntries()
    'Put appropriate entries in ListBox1
    Dim QID, finish, start, cell, cell2 As String
    Dim row As Integer
    row = ActiveWindow.ActiveCell.row
    cell = "A" & row
    QID = Worksheets("SingleLevel2").Range(cell).Value
    For Counter = 2 To 5
        cell2 = "A" & Counter
        If Worksheets("Sheet1").Range(cell2).Value = QID Then
            start = Counter
            Exit For
        End If
    Next Counter
    For Counter = 2 To 5
        cell2 = "A" & Counter
        If Worksheets("Sheet1").Range(cell2).Value = QID Then
            finish = Counter
        End If
    Next Counter
    If start <> "" And finish <> "" Then
        ListBox1.RowSource = "=Sheet1!$B$" & start & ":$C$" & finish
    End If
    End Sub
    
    Private Sub cmdCancel_Click()
    Unload Me
    End Sub
    
    Private Sub cmdCustom_Click()
    Dim i As Integer, s As String
    With ListBox1
        i = .ListIndex
        i = i + 1
        .AddItem , i
        s = InputBox("Please enter a commnent: ")
        If s = "" Then
            .RemoveItem i
        Else
            .List(i, 0) = s
            s = InputBox("Please enter a remedial action: ")
            .List(i, 1) = s
        End If
    End With
    End Sub

    So if I understand you correctly, I would use the beforeDoubleClick event to unhide the form if the target is in a range of cells the userform applies to, and do nothing if it is not. Correct? But do I need to start the form hidden when the file is opened or will this event work regardless? And what would be the easiest way to specify a few ranges of cells? There are too many to specify individually.

    Last edited by Rikki_UW; Sep 15th, 2008 at 10:27 AM.


  10. Sep 15th, 2008, 11:33 AM


    #10

    Re: HELP dynamic listbox with checkbox column on VBA form

    few observations/questions

    1) Your start and finish values will always be equal as you are looping thru same set of cells and doing the same comparison.

    2) This

    For Counter = 2 To 5
    cell2 = «A» & Counter
    If Worksheets(«Sheet1»).Range(cell2).Value = QID Then
    finish = Counter
    End If
    Next Counter

    can also be written as

    Code:

    For Counter = 2 To 5
        If Worksheets("Sheet1").Range("A" & Counter).Value = QID Then
            finish = Counter
        End If
    Next Counter

    3) Specifying a range is not a problem but what exactly do you want to achieve by specifying the range. One way to specify a range…

    Code:

    'This is just an example
    Dim Rng as Range
    Set rng = Worksheets("Sheet1").Range("A1:A40")

    4) Regarding the userform you can show when a user double clicks a cell as per your requirement.

    5) The code that I gave above has to be place in the worksheet code window

    something like

    Code:

    Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
        UserForm1.Show
    End Sub

    Hope this helps…

    A good exercise for the Heart is to bend down and help another up…
    Please Mark your Thread «Resolved», if the query is solved

    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27″ 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero


  11. Sep 15th, 2008, 12:20 PM


    #11

    Rikki_UW is offline

    Thread Starter


    Addicted Member


    Re: HELP dynamic listbox with checkbox column on VBA form

    1) I have Exit For for the start but not for the finish, it works I’ve tested it
    2) of course, missed that, thanks

    3/4/5) the double click code works, I had it in the wrong place but I’ve corrected it, the problem is that it should only unhide for certain ranges of cells (E22 to F28, E30 to F36, etc. unfortunately there are a lot of them). I tried the following code but got the error «compile error: sub or function not defined»:

    Code:

    Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    If ActiveCell = Worksheet("SingleLevel2").Range(E22, F28) Then
        UserForm1.Show
    End If
    Cancel = False
    End Sub


  12. Sep 15th, 2008, 03:19 PM


    #12

    Re: HELP dynamic listbox with checkbox column on VBA form

    unfortunately there are a lot of them

    How many of them???? I need to know that so that we can put that in code….

    A good exercise for the Heart is to bend down and help another up…
    Please Mark your Thread «Resolved», if the query is solved

    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27″ 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero


  13. Sep 15th, 2008, 03:28 PM


    #13

    Rikki_UW is offline

    Thread Starter


    Addicted Member


    Re: HELP dynamic listbox with checkbox column on VBA form

    E22 to F28, E30 to F36, E41 to F47, E53 to F67, E69 to F77, E79 to F87, E93 to F98, E100 to F103, E105 to F108, E110 to F125, E130 to F144, E146 to F150

    Also merged cells CDE162 and CDE165, bringing the grand total to 14 sections


  14. Sep 15th, 2008, 03:49 PM


    #14

    Re: HELP dynamic listbox with checkbox column on VBA form

    Try this. It is commented so I don’t think it will be difficult to understand. However if you still have questions, do ask.

    vb Code:

    1. Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

    2. Dim rng As Range, cell As Range

    3. 'The range needs to be put within quotes separated by ":" and distinguised by ","

    4. 'for example I have taken 3 range into consideration

    5. 'E22 to F28, E30 to F36, E41 to F47. I am sure now you will be able to integrate

    6. 'The rest of them in the line below.

    7. Set rng = Range("E22:F28,E30:F36,E41:F47")

    8. For Each cell In rng

    9.     If ActiveCell.Address = cell.Address Then

    10.         UserForm1.Show

    11.         'Exit the moment you find the 1st match to prevent a loop

    12.         Exit For

    13.     End If

    14.     Cancel = False

    15. Next

    16. End Sub

    A good exercise for the Heart is to bend down and help another up…
    Please Mark your Thread «Resolved», if the query is solved

    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27″ 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero


  15. Sep 16th, 2008, 08:51 AM


    #15

    Rikki_UW is offline

    Thread Starter


    Addicted Member


    Re: HELP dynamic listbox with checkbox column on VBA form

    Thank you that makes sense, I didn’t know you could have multiple ranges in one range object.

    The last thing i need to do is to insert the text from the selected rows into the appropriate cells. There are two columns and each column will go in a separate cell, but all rows selected will go in the same two cells. I have managed to get it to work but I need the column height but NOT width to resize to fit automatically.

    Code:

    Dim comments, actions As String
    Dim i, row As Integer
    comments = ""
    With UserForm1.ListBox1
        For i = 0 To .ListCount - 1
            If .selected(i) Then
                If comments = "" Then
                    comments = .List(i)
                Else
                    comments = comments & Chr(10) & .List(i)
                End If
            End If
        Next i
    End With
    
    With UserForm1.ListBox1
        For i = 0 To .ListCount - 1
            If .selected(i) Then
                If actions = "" Then
                    actions = .List(i, 1)
                Else
                    actions = actions & Chr(10) & .List(i, 1)
                End If
            End If
        Next i
    End With
    
    row = ActiveWindow.ActiveCell.row
    Worksheets("Single Level 2").Range("E" & row).Value = comments
    Worksheets("Single Level 2").Range("F" & row).Value = actions

    Thanks,
    —Rikki

    Last edited by Rikki_UW; Sep 16th, 2008 at 09:45 AM.


  16. Sep 16th, 2008, 11:12 AM


    #16

    Rikki_UW is offline

    Thread Starter


    Addicted Member


    Re: HELP dynamic listbox with checkbox column on VBA form

    Never mind, got it working, my boss will be reviewing it this afternoon so I will post back if I need any more help. In the meantime, thanks a lot!

    —Rikki

    Last edited by Rikki_UW; Sep 16th, 2008 at 11:52 AM.


  17. Sep 16th, 2008, 12:03 PM


    #17

    Re: HELP dynamic listbox with checkbox column on VBA form

    Sorry for the late reply… was in a meeting for 3 hours… Man!!!! I am mentally very exhausted

    Anyways great it is solved… do let me know how did your boss like it

    A good exercise for the Heart is to bend down and help another up…
    Please Mark your Thread «Resolved», if the query is solved

    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27″ 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero


  18. Sep 16th, 2008, 02:18 PM


    #18

    Rikki_UW is offline

    Thread Starter


    Addicted Member


    Re: HELP dynamic listbox with checkbox column on VBA form

    No problem. Wow that does sound tiring, not to mention boring lol. Anyway, he was pleased with it. One error I didn’t notice though, which I fixed and led to another, which I fixed, which uncovered another that I’m stumped on.

    Here is the method which gets correct entries from other sheet. It relies on them being in numerical order according to QID, which was fine until I added the ability to add custom comments making them no longer in numerical order, so I need a way to add them individually instead of in a group. I tried using ListBox1.addItem but can’t figure out how to use the method.

    Code:

    Private Sub FindEntries()
    'Put appropriate entries in ListBox1
    Dim QID, finish, start As String
    Dim row As Integer
    row = ActiveWindow.ActiveCell.row
    QID = Worksheets("Single Level 2").Range("A" & row).Value
    For Counter = 2 To 300
        If Worksheets("Comments").Range("A" & Counter).Value = QID Then
            start = Counter
            Exit For
        End If
    Next Counter
    For Counter = 2 To 300
        If Worksheets("Comments").Range("A" & Counter).Value = QID Then
            finish = Counter
        End If
    Next Counter
    If start <> "" And finish <> "" Then
        ListBox1.RowSource = "=Comments!$B$" & start & ":$C$" & finish
    End If
    
    txtProblem.Value = Worksheets("Single Level 2").Range("C165").Value
    txtAction.Value = Worksheets("Single Level 2").Range("C168").Value
    End Sub


  19. Sep 16th, 2008, 02:35 PM


    #19

    Re: HELP dynamic listbox with checkbox column on VBA form

    One error I didn’t notice though, which I fixed and led to another, which I fixed, which uncovered another that I’m stumped on.

    That’s best way to learn

    I would do it like this (logic)

    loop 1
    if condition 1
    ListBox1.addItem Worksheets(«xyz»).Range(«abc»).Value
    end condition
    end of loop1

    A good exercise for the Heart is to bend down and help another up…
    Please Mark your Thread «Resolved», if the query is solved

    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27″ 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero


  20. Sep 16th, 2008, 02:47 PM


    #20

    Rikki_UW is offline

    Thread Starter


    Addicted Member


    Re: HELP dynamic listbox with checkbox column on VBA form

    That almost works, but how do I get the 2nd column? putting range as B3:C3 (for example) doesn’t work.


  21. Sep 16th, 2008, 03:05 PM


    #21

    Re: HELP dynamic listbox with checkbox column on VBA form

    In a ListBox or ComboBox with a single column, the AddItem method provides an effective technique for adding an individual entry to the list. In a multicolumn ListBox or ComboBox, however, the List and Column properties offer another technique; you can load the list from a two-dimensional array.

    A good exercise for the Heart is to bend down and help another up…
    Please Mark your Thread «Resolved», if the query is solved

    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27″ 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero


  22. Sep 16th, 2008, 03:26 PM


    #22

    Rikki_UW is offline

    Thread Starter


    Addicted Member


    Re: HELP dynamic listbox with checkbox column on VBA form

    Okay, I’ve never used arrays in VB before. This is what I have, but how do I use the List property to load the list from my 2d array?

    Code:

    Private Sub FindEntries()
    ListBox1.Clear
    'Put appropriate entries in ListBox1
    Dim QID, finish, start As String
    Dim row, i As Integer
    Dim comments(50, 2) As String
    i = 0
    row = ActiveWindow.ActiveCell.row
    QID = Worksheets("Single Level 2").Range("A" & row).Value
    For Counter = 2 To 300
        If Worksheets("Comments").Range("A" & Counter).Value = QID Then
            comments(i, 0) = Worksheets("Comments").Range("B" & Counter).Value
            comments(i, 1) = Worksheets("Comments").Range("C" & Counter).Value
            i = i + 1
    '        start = Counter
    '        Exit For
        End If
    Next Counter
    ListBox1.List(0, 0) comments
    'For Counter = 2 To 300
    '    If Worksheets("Comments").Range("A" & Counter).Value = QID Then
    '        finish = Counter
    '    End If
    'Next Counter
    If start <> "" And finish <> "" Then
        ListBox1.RowSource = "=Comments!$B$" & start & ":$C$" & finish
    End If
    
    txtProblem.Value = Worksheets("Single Level 2").Range("C165").Value
    txtAction.Value = Worksheets("Single Level 2").Range("C168").Value
    End Sub


  23. Sep 16th, 2008, 03:34 PM


    #23

    Re: HELP dynamic listbox with checkbox column on VBA form

    Here are two examples

    Code:

        Set rngSource = Worksheets("xyz").Range("A1:k1500") 'you can combine ranges here
        With ListBox1
            
            'Insert the range of data supplied
            .List = rngSource.Cells.Value
        End With

    or with arrays

    you need to transfer the values into an array and then follow the above example to set the range

    Code:

        With ListBox1
            
            'Insert the range of data supplied
            .List = Ar1 'where Ar1 is a 2d array as required
        End With

    A good exercise for the Heart is to bend down and help another up…
    Please Mark your Thread «Resolved», if the query is solved

    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27″ 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero


  24. Sep 16th, 2008, 04:00 PM


    #24

    Rikki_UW is offline

    Thread Starter


    Addicted Member


    Re: HELP dynamic listbox with checkbox column on VBA form

    Getting closer. Couldn’t get the array method to work because I didn’t know size before and ended up with blanks, got too complicated so I’m using the first method. creating a range object made up of various ranges and adding it outside the loop only added the first entry, adding them inside the loop constantly overrides the first row so the last entry is the only one there. Here is what I have for that:

    Code:

    For Counter = 2 To 300
        If Worksheets("Comments").Range("A" & Counter).Value = QID Then
                Set rng = Worksheets("Comments").Range("B" & Counter & ":C" & Counter)
                ListBox1.List = rng.Cells.Value
        End If
    Next Counter


  25. Sep 16th, 2008, 04:29 PM


    #25

    Re: HELP dynamic listbox with checkbox column on VBA form

    Try something like this

    vb Code:

    1. Private Sub FindEntries()

    2.     Dim QID, finish, start As String

    3.     Dim row, i As Integer

    4.     Dim comments(50, 1) As String

    5.     ListBox1.Clear

    6.     i = 0

    7.     row = ActiveWindow.ActiveCell.row

    8.     QID = Worksheets("Single Level 2").Range("A" & row).Value

    9.     For Counter = 2 To 300

    10.         If Worksheets("Comments").Range("A" & Counter).Value = QID Then

    11.             comments(i, 0) = Worksheets("Comments").Range("B" & Counter).Value

    12.             comments(i, 1) = Worksheets("Comments").Range("C" & Counter).Value

    13.             i = i + 1

    14.         End If

    15.     Next Counter

    16.     ListBox1.List = comments

    17.     'REST OF CODE AS APPLICABLE

    18. End Sub

    A good exercise for the Heart is to bend down and help another up…
    Please Mark your Thread «Resolved», if the query is solved

    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27″ 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero


  26. Sep 16th, 2008, 04:34 PM


    #26

    Re: HELP dynamic listbox with checkbox column on VBA form

    Here is a basic example to understand how array works…

    Create a blank userform. on it create a listbox

    type this in the code

    Code:

    Private Sub UserForm_Initialize()
        Dim ar(3, 1)
        ar(0, 0) = 1
        ar(0, 1) = 2
        ar(1, 0) = 3
        ar(1, 1) = 4
        ar(2, 0) = 5
        ar(2, 1) = 6
        ar(3, 0) = 7
        ar(3, 1) = 8
        
        ListBox1.ColumnCount = 2
        ListBox1.List = ar
    End Sub

    Hope this helps…

    A good exercise for the Heart is to bend down and help another up…
    Please Mark your Thread «Resolved», if the query is solved

    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27″ 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero


  27. Sep 17th, 2008, 08:00 AM


    #27

    Rikki_UW is offline

    Thread Starter


    Addicted Member


    Re: HELP dynamic listbox with checkbox column on VBA form

    Thanks, I understand the array concept better, but the problem was that I don’t know how many entries will be in the array, and any extra ones end up as empty checkboxes.

    I managed to create a second array of the right length instead, here is the final code:

    vb Code:

    1. ListBox1.Clear

    2. 'Put appropriate entries in ListBox1

    3. Dim QID As String

    4. Dim row, i, length As Integer

    5. Dim comments(20, 1) As String

    6. i = 0

    7. length = 0

    8. row = ActiveWindow.ActiveCell.row

    9. QID = Worksheets("Single Level 2").Range("A" & row).Value

    10. For Counter = 2 To 300

    11.     If Worksheets("Comments").Range("A" & Counter).Value = QID Then

    12.             comments(i, 0) = Worksheets("Comments").Range("B" & Counter).Value

    13.             comments(i, 1) = Worksheets("Comments").Range("C" & Counter).Value

    14.             i = i + 1

    15.     End If

    16. Next Counter

    17. For Counter = 0 To 19

    18.     If comments(Counter, 0) <> "" Or comments(Counter, 1) <> "" Then

    19.         length = length + 1

    20.     End If

    21. Next Counter

    22. Dim comments2() As String

    23. If length > 0 Then

    24.     ReDim comments2(length - 1, 1) As String

    25.     For Counter = 0 To (length - 1)

    26.         comments2(Counter, 0) = comments(Counter, 0)

    27.         comments2(Counter, 1) = comments(Counter, 1)

    28.     Next Counter

    29.     ListBox1.List = comments2

    30. End If


  28. Sep 17th, 2008, 10:51 AM


    #28

    Rikki_UW is offline

    Thread Starter


    Addicted Member


    Re: HELP dynamic listbox with checkbox column on VBA form

    Almost lol, one more quickie, is it possible to have multiple lines for one checkbox? some of the text is being cut off and I can’t make the listbox much bigger.

    Also, my employer would like a grid behind the listbox but I don’t see that under properties, is it possible to do?


  29. Sep 17th, 2008, 01:59 PM


    #29

    Re: HELP dynamic listbox with checkbox column on VBA form

    Checkbox1.wordwrap = True
    Checkbox1.Height = whatever you feel is feasible

    Grid as in backlines?

    A good exercise for the Heart is to bend down and help another up…
    Please Mark your Thread «Resolved», if the query is solved

    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27″ 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero


  30. Sep 17th, 2008, 02:12 PM


    #30

    Rikki_UW is offline

    Thread Starter


    Addicted Member


    Re: HELP dynamic listbox with checkbox column on VBA form

    My bad I meant checkboxes as in the entries in the listbox, correct me if I’m wrong but I don’t think that’s possible.

    Gridlines as in like the gray cell outlines on the spreadsheet, or at least something to separate the columns, as it can be hard to read with no space/divider between the two.


  31. Sep 18th, 2008, 07:21 AM


    #31

    Re: HELP dynamic listbox with checkbox column on VBA form

    Gridlines: I don’t think this is possible in vba FOR LISTBOX … but I could be wrong…

    A good exercise for the Heart is to bend down and help another up…
    Please Mark your Thread «Resolved», if the query is solved

    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27″ 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero


  • Home
  • VBForums
  • Visual Basic
  • Office Development
  • [RESOLVED] HELP dynamic listbox with checkbox column on VBA form


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

Понравилась статья? Поделить с друзьями:
  • Excel vba bit and
  • Excel vba chart setsourcedata
  • Excel vba bad file name or number
  • Excel vba char string
  • Excel vba background color