Sie sind auf Seite 1von 14

1

Create a ComboBox
In an Excel UserForm, you can create drop down lists by using the ComboBox control. In this
example, the UserForm has two ComboBox controls, one for Part ID, and one for Location.
A ComboBox can have a single column, like this list of location names.

Or a ComboBox can have multiple columns, like this parts list that shows both the Part ID and a Part
Description.

This Excel VBA example is based on the instructions for Creating an Excel UserForm With
ComboBoxes.
On that page, the Excel VBA code is listed, but not explained in detail. In this tutorial, we'll look at how
the Excel ComboBox code works. First, we'll create VBA code for a single column ComboBox list, and
then we'll create Excel VBA code for a ComboBox with two columns.
Single Column ComboBox
This Excel UserForm has a ComboBox named cboLocation. We want this ComboBox to show all the
locations from a named range -- LocationList -- on the LookupLists worksheet.

2


There is only one column in the list on the worksheet, so we'll only need one column in the
ComboBox.
We'd like the ComboBox lists to be created automatically, when someone opens our UserForm. To do
that, we'll use the Initialize event for the UserForm.
1. In the Visual Basic Editor (VBE), select the UserForm, and on the Menu bar, click
View, then click Code.
2. In the dropdown at the top left of the VBE, select UserForm (it may be selected
already).
3. From the Procedure dropdown, at the top right, choose Initialize

4. The Initialize event code is added to the Excel VBA code module, with Sub and
End Sub lines only. The cursor is flashing between the first and last line of code.

Define the Variables
Where the cursor is flashing in the Initialize procedure, we'll define two variables to be used in the
procedure:
Private Sub UserForm_Initialize()


Dim cLoc As Range
Dim ws As Worksheet
Set ws = Worksheets("LookupLists")

End Sub

3

The cLoc variable is a Range object, and we'll use it to refer to a cell in the LocationList range on the
worksheet.
The ws variable is a Worksheet object, and we Set it to the LookupLists worksheet, where the
Location list is stored.
Add a Loop
Next, we'll add a For Each...Next loop, that will visit each cell in the LocationList range on the
LookupLists worksheet.
Private Sub UserForm_Initialize()
Dim cLoc As Range
Dim ws As Worksheet
Set ws = Worksheets("LookupLists")

For Each cLoc In ws.Range("LocationList")

Next cLoc

End Sub
Add the With...End With
Next, we'll add a With...End With statement, that refers to the Location ComboBox, which is named
cboLocation. This code is on the UserForm module, so Me refers to the UserForm.
For Each cLoc In ws.Range("LocationList")
With Me.cboLocation

End With
Next cLoc
Add the List Items
Finally, inside the With...End With, we'll put the code to add the list items. The AddItem method adds an item to the
) in the LocationList range. cLoc ComboBox, and our code tell Excel to use the value from the current cell (
Range("LocationList") For Each cLoc In ws.
With Me.cboLocation
.AddItem cLoc.Value
End With
Next cLoc
If you test the UserForm with this Initialize code, the Location ComboBox will have a single column drop down, showing
The Part ComboBox will have an empty drop down list, because we haven't all four locations from the LocationList range.
added any items to it yet.


4

Multiple Column ComboBox
-- . It will show the Part IDs from a named range cboPart Next, we'll add items to the Part ComboBox, which is named
on the LookupLists worksheet. -- PartIDList

There are two columns in the Parts list on the worksheet, so we'll need two columns in the ComboBox, with Part ID in the
first column, and Part Description in the second column.
Add a Variable
ze procedure, we'll add another variable, for the cells in the Part ID list on the worksheet. At the top of the Initiali
Private Sub UserForm_Initialize()
Dim cPart As Range
Dim cLoc As Range
Dim ws As Worksheet
Set ws = Worksheets("LookupLists")
variable is a Range object, and we'll use it to refer to a cell in the PartIDList range on the worksheet. cPart The
Add a Loop
Next, we'll add a For Each...Next loop, that will visit each cell in the PartIDList range on the LookupLists worksheet.
rm_Initialize() Private Sub UserFo
Dim cLoc As Range
Dim ws As Worksheet
Set ws = Worksheets("LookupLists")
For Each cPart In ws.Range("PartIDList")
Next cPart
Add the With...End With

5

. This code is on cboPart ed Next, we'll add a With...End With statement, that refers to the Part ComboBox, which is nam
refers to the UserForm. Me the UserForm module, so
For Each cPart In ws.Range("PartIDList")
With Me.cboPart

End With
Next cPart
Add the List Items
ms. The AddItem method adds a row to the Next, inside the With...End With, we'll put the code to add the list ite
) in the PartIDList range in the first column of the drop down. cPart ComboBox, with the value from the current cell (
For Each cPart In ws.Range("PartIDList")
With Me.cboPart
.AddItem cPart.Value
End With
Next cPart
Add the Second Column Values
Next, below the AddItem code, we'll put the code to add the values in the second column, using the List property. Our
umber of items in the code will tell Excel which row and column of the drop down to use. The ListCount property is the n
drop down list.
For the List property, both the Row and Column counts start at zero. So, if there is 1 item in the drop down list, it is in
Row 0. That's why we subtract 1 from the ListCount, to get the Row number.
Description in the second column. The first column is 0, so the second column is Column 1. We want our Part
For Each cPart In ws.Range("PartIDList")
With Me.cboPart
.AddItem cPart.Value
1, 1) = cPart.Offset(0, 1).Value - .List(.ListCount
End With
Next cPart
cPart cell is in column A, and we want the Part Description from column B in the same row. So, we use the Offset The
property to get the value that is 0 rows down, and 1 column to the right.
Change the ComboBox Properties

6

, change the ComboBox properties, to increase the number of columns, and set For ComboBoxes with multiple columns
the column widths. You can also show column headings, if you'd like.

The Completed Excel VBA Code
Here's the completed Excel VBA code for the UserForm Initialize procedure. It adds the single column list in the Location
ComboBox, and the two column list in the Part ComboBox.
Private Sub UserForm_Initialize()
Dim cPart As Range
Dim cLoc As Range
Dim ws As Worksheet
Set ws = Worksheets("LookupLists")

For Each cPart In ws.Range("PartIDList")
With Me.cboPart
.AddItem cPart.Value
.List(.ListCount - 1, 1) = cPart.Offset(0, 1).Value
End With
Next cPart

For Each cLoc In ws.Range("LocationList")
With Me.cboLocation
.AddItem cLoc.Value
End With
Next cLoc

Me.txtDate.Value = Format(Date, "Medium Date")
Me.txtQty.Value = 1
Me.cboPart.SetFocus

End Sub
At the end, the Excel VBA code puts the current date in the Date text box, and the number 1 in the Quantity text box.
The SetFocus method moves the cursor to the Part ComboBox, so it's ready for the user to select a part.
Watch the Excel VBA ComboBox video

7

Create an Excel UserForm
To create a UserForm requires some programming, and
the steps are clearly outlined below.
In this example, inventory data is stored on a hidden
worksheet, where it is protected from accidental damage
or deletion.
Users enter inventory data by opening the UserForm,
filling in the boxes, and clicking a button.
To view the steps in a short video, click here (video is in 3
parts).
Set up the worksheet
In this example, a parts inventory is stored on a hidden
worksheet.

1. Open a new workbook
2. Double-click on the sheet tab for Sheet1
3. Type: PartsData
4. Press the Enter key
5. In cells A1:D1, enter the headings for the parts
inventory database, as shown at right.
6. Choose File | Save, and save the workbook. In this
example, the file has been named PartsLocDB.xls.


A B C D
1 PartID Location Date Qty
2 12345
Store
001
3/3/2004 87
3

Create an Excel UserForm
Excel UserForms are created in the Visual Basic
Editor.
1. To open the Visual Basic Editor, hold the Alt
key, and press the F11 key
2. Choose View | Project Explorer, to see a list
of projects. (Usually, this is displayed at the
left side of the VBE window.)
3. In the Project Explorer, select the
PartLocDB project.
4. From the menu bar, choose Insert |
UserForm
5. A blank UserForm appears, and the
ToolBox should open. (If the ToolBox
doesn't appear, choose View | Toolbox)


8

Name the Excel UserForm
1. To open the Properties window, press the
F4 key
2. In the Properties window, double-click on
the Name -- UserForm1, at the top right of
the window.
3. Type: frmPartLoc
and press the Enter key
4. The form name will change in the Project
Explorer, but the form still shows
UserForm1 in its title bar.
5. In the Properties window, double-click on
the Caption property-- UserForm1.
6. Type: Parts Inventory
and press the Enter key
7. The title bar will display the new caption.

Add a Textbox to the Excel
UserForm
The objects on an Excel UserForm, such as
buttons, and textboxes, are called controls. To
allow users to enter data, you can add textbox
controls to the form, with label controls to describe
them.
1. In the Toolbox, click on the TextBox button.
2. On the UserForm, click near the top centre,
to add a standard sized textbox.
3. With the new textbox selected, double-click
on the Name property in the Properties
window.
4. Type: txtPart
and press the Enter key
5. Click on an empty part of the UserForm, to
select the UserForm and to display the
Toolbox.



9

Add a Label to the Excel
UserForm
To help users enter data, you can add label
controls to describe the textboxes, or to display
instructions.
1. In the Toolbox, click on the Label button.
2. On the UserForm, click to the left of the
textbox, to add a standard sized label.
3. With the new label selected, double-click on
the Caption property in the Properties
window.
4. Type: Part
and press the Enter key
5. If necessary, you can resize the label, so it
doesn't cover the textbox -- point to the
handle on its right border, and drag to the
left.
6. Click on an empty part of the UserForm, to
select the UserForm and to display the
Toolbox.


To view the steps in a short video, click here
(video is in 3 parts).
Add remaining textboxes and
labels
Repeat the above steps to add:
a textbox named txtLoc, with a
label Location
a textbox named txtDate, with a label Date
a textbox named txtQty, with a
label Quantity
If the textboxes are not aligned, you can align them:
1. Click on the first textbox
2. Hold the Ctrl key, and click on the remaining
textboxes
3. Choose Format | Align | Lefts
4. Click on an empty part of the UserForm, to
select the UserForm and to display the
Toolbox.



10

Add Buttons to the Excel
UserForm
To allow users to perform an action, you can add
command buttons to the user form. This form has a
button to add data to the database, and a button to
close the form.
1. In the Toolbox, click on the CommandButton
button.
2. On the UserForm, click at the bottom left, to
add a standard sized CommandButton.
3. With the new CommandButton selected,
double-click on the Name property in the
Properties window.
4. Type: cmdAdd
and press the Enter key
5. With the new CommandButton selected,
double-click on the Caption property in the
Properties window.
6. Type: Add this part
and press the Enter key
7. Click on an empty part of the Excel
UserForm, to select the UserForm and to
display the Toolbox.
8. Repeat the above steps to add a
CommandButton named cmdClose, with a
label Close
9. If required, you can reposition the buttons
by dragging them to a new location on the
UserForm.






To view the steps in a short video, click here
(video is in 3 parts).

11

Add code to the buttons
To make the Excel UserForm buttons perform an action,
you create code that runs when the button is clicked.
Add code to the cmdAdd button
1. Select the cmdAdd button
2. On the Menu bar, choose View | Code.
3. This creates a procedure, where you can add your
code.
4. Where the cursor is flashing, enter the following
code:
Private Sub cmdAdd_Click()
Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("PartsData")

'find first empty row in database
iRow = ws.Cells.Find(What:="*",
SearchOrder:=xlRows, _
SearchDirection:=xlPrevious,
LookIn:=xlValues).Row + 1

'check for a part number
If Trim(Me.txtPart.Value) = "" Then
Me.txtPart.SetFocus
MsgBox "Please enter a part number"
Exit Sub
End If

'copy the data to the database
ws.Cells(iRow, 1).Value = Me.txtPart.Value
ws.Cells(iRow, 2).Value = Me.txtLoc.Value
ws.Cells(iRow, 3).Value = Me.txtDate.Value
ws.Cells(iRow, 4).Value = Me.txtQty.Value

'clear the data
Me.txtPart.Value = ""
Me.txtLoc.Value = ""
Me.txtDate.Value = ""
Me.txtQty.Value = ""
Me.txtPart.SetFocus

End Sub
5. On the Menu bar, choose View | Object, to return to
the UserForm.






12

Test the Excel UserForm
To test the form, you can run it from the VBE.
1. Click on an empty part of the UserForm, to
select the UserForm and to display the
Toolbox.
2. On the Menu bar, choose Run | Run
Sub/UserForm.
3. In the Part textbox, type: 12345
4. Press the tab key to move to the next textbox.
5. When the textboxes have been filled in, click
the 'Add this part' button.
6. Click the 'Close form' button, to return to the
VBE.
If the tab order was incorrect (e.g. when you pressed
the tab key you moved to the wrong textbox or button),
you can change it
1. Right-click on an empty part of the UserForm
2. Choose Tab Order
3. Select a control in the list, and click the Move
Up or Move Down button
4. Click OK




13

Create a Button to open the Excel UserForm
To make it easy for users to open the UserForm, you can add a button to a worksheet.
1. Switch to Excel, and activate the PartLocDB.xls workbook
2. Double-click on the sheet tab for Sheet2
3. Type: Parts Data Entry
4. Press the Enter key
5. On the Drawing toolbar, click on the Rectangle tool
6. In the centre of the worksheet, draw a rectangle, and format as desired.
7. With the rectangle selected, type:
Click here to add Part Information
8. Right-click on the rectangle border, and choose 'Assign Macro'
9. Click the New button
10. Where the cursor is flashing, type: frmPartLoc.Show
Note: If you are using Excel 2000, or later version, and want users to be able to do other
things while the form is open, change the above line to:
frmPartLoc.Show False
To prevent users from closing the form by clicking the X button:
1. Right-click on an empty part of the UserForm
2. Choose View | Code
3. Scroll to the bottom of the existing code, and enter the following code:
Private Sub UserForm_QueryClose(Cancel As Integer, _
CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
Cancel = True
MsgBox "Please use the button!"
End If
End Sub
4. On the Menu bar, choose View | Object, to return to the UserForm.
Add code to the cmdClose button
1. Select the cmdClose button
2. On the Menu bar, choose View | Code.
3. Where the cursor is flashing, enter the
following code:
Private Sub cmdClose_Click()
Unload Me
End Sub
4. On the Menu bar, choose View | Object, to
return to the UserForm.
To allow users to close the form by pressing the
Esc key:
1. Select the cmdClose button
2. In the Properties window, change the Cancel




View the steps in a
short Excel UserForm video
(video is in 3 parts).

14

property to True

Das könnte Ihnen auch gefallen