Discussion Locked

Creating Command Buttons w/Captions

0 helpful
5 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

I need to be able to dynamically (programmatically) create 'X' number of Command Buttons on a form based on data in a table. (e.g. if the table contains 10 records, I need ten Command Buttons with the LastName field shown as the caption on the button) I (think I) know this involves creating and using RecordSets and MoveNext, MoveFirst commands etc.

Is there a SIMPLE tutorial on creating and using Recordsets? (I've been through the Access VBA Help - no help - that's why I'm asking here!)

Also, any help (code examples?) with my specific problem would be GREATLY appreciated.

5 replies

by peyison

I assume you're working in Access, not VB. I don't think there is a way to dynamically create controls in Access, but what you could do is create the maximum number of buttons you'll need and hide them. Then, based on the results of the query, show only the ones you need. Here is an example of how that might work:

Create a form with 5 Command Buttons called cmdButton1, cmdButton2 ... cmdButton5
set the visible property of all buttons to no

Put this code in the event that will be creating the buttons (e.g. Form_Load):

Dim db as Database
Dim rst as RecordSet
Dim Command as CommandButton
Dim sSql as String
Dim iIndex as Integer

sSql = "Select LastName From tblUsers Order By LastName"
Set db = DBEngine(0)(0)
Set rst = db.OpenRecordset(sSql)
iIndex = 0

Do Until rst.EOF
iIndex = iIndex + 1
Select case iIndex
Case 1
Set Command = cmdButton1
Case 2
Set Command = cmdButton2
Case 3
Set Command = cmdButton3
Case 4
Set Command = cmdButton4
Case 5
Set Command = cmdButton5
End Select

Command.Caption = rst!LastName
Command.Visible = True

rst.MoveNext
Loop

Set Command = Nothing
rst.Close
Set rst = Nothing
set db = Nothing

Access doesn't support control arrays either - that's why we need the select case code. In VB this would be easier using a control array.

Hope this helps.

This discussion is closed to new replies.