annoying problem with creating controls at runtime

M

Mamiju

Hi,
I do have a little trouble with creating a form with buttons at runtime.
Environment: Access 2002, Visual Basic Editor

If I run the Sub TestOpenOrCreateForm in F8 mode or if I set Breakpoints in
front of AddOrChangeButton then it works fine.

However the sub fails when I run it with F5.
If I run it with F5 then only the first button is created.

Any ideas?


Option Compare Database
Option Explicit

rem this either opens a given form or creates a new one with the name saveas
Function OpenOrCreateForm(SaveAs, Caption As String) As Form
Dim frm As Form
Dim doc As Document
Dim db As Database
Set db = CurrentDb
For Each doc In db.Containers("forms").Documents
If doc.Name = SaveAs Then
DoCmd.OpenForm SaveAs, acDesign
Set frm = Application.Forms(SaveAs)
Set OpenOrCreateForm = frm
Exit Function
End If
Next
Set frm = Application.CreateForm
frm.Caption = Caption
SendKeys SaveAs & "{ENTER}", False
Application.RunCommand acCmdSaveAs
Set OpenOrCreateForm = frm
End Function

Sub AddOrChangeButton(frm As Form, btn_name, btn_caption As String, left,
top, width, height As Long)
Dim objControl As control
For Each objControl In frm.Controls
If objControl.Name = btn_name Then
objControl.Properties("caption").Value = btn_caption
objControl.Properties("left").Value = left
objControl.Properties("top").Value = top
objControl.Properties("width").Value = width
objControl.Properties("height").Value = height
Exit Sub
End If
Next
Set objControl = CreateControl(frm.Name, acCommandButton, acDetail, , , 250,
250, 1000, 400)
objControl.Properties("caption").Value = btn_caption
objControl.Properties("name").Value = btn_name
End Sub

Sub TestOpenOrCreateForm()
Dim frm As Form
Dim control As control
Set frm = OpenOrCreateForm("HelloWorld", "Hallo Welt")
Debug.Print frm.Name
AddOrChangeButton frm, "HalloWelt", "Hallo Meine Welt", 250, 250, 2500, 400
AddOrChangeButton frm, "2ndWelt", "Zweite Meine Welt", 250, 750, 2500, 400
AddOrChangeButton frm, "3ndWelt", "Dritte Meine Welt", 250, 1250, 2000, 400
Application.RunCommand acCmdSave
Application.RunCommand acCmdClose
End Sub
 
G

George Nicholson

Sounds like a timing issue. Try adding a few DoEvents, especially after
issuing Saving, Creating or Opening instructions and see if that helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top