How to disable a button in its click event?

  • Thread starter Thread starter GZ
  • Start date Start date
G

GZ

Hi,
I need disable a button after it is clicked.
But cmdButton.Enabled = False cannot be executed because it is in focus.
Any good idea?
Thanks!
GZ
 
You need to set the focus to another control ...

Me!SomeOtherControl.SetFocus
Me!cmdButton.Enabled = False

--
Brendan Reynolds (MVP)
http://brenreyn.blogspot.com

The spammers and script-kiddies have succeeded in making it impossible for
me to use a real e-mail address in public newsgroups. E-mail replies to
this post will be deleted without being read. Any e-mail claiming to be
from brenreyn at indigo dot ie that is not digitally signed by me with a
GlobalSign digital certificate is a forgery and should be deleted without
being read. Follow-up questions should in general be posted to the
newsgroup, but if you have a good reason to send me e-mail, you'll find
a useable e-mail address at the URL above.
 
Set focus to something else before you try to disable it, e.g.:
Me.[Text1].SetFocus
Me.cmdButton.Enabled = False
 
You are correct that you cannot disable a control while it has the focus.
This is because the control is enjoying it's "five minutes of fame" and does not want to give it up.

The trick is to move the focus elsewhere first and then disable the command button. You can move the
focus to any other control or perhaps even a tiny little text box control with 0" dimensions which
will not be seen.

So something like this should work:

Private Sub cmdMyButton_Click()
' Move the focus to another control
Me.txtFocus.SetFocus
' Disable the command button
Me.cmdMyButton.Enabled = False
' Code to do whatever you would like here
' Yadda, yadda
End Sub

Or you could do all this in a separate sub procedure like so:

Private Sub cmdMyButton_Click()
Call subOtherCode
End Sub

Private Sub subOtherCode()
' Move the focus to another control
Me.txtFocus.SetFocus
' Disable the command button
Me.cmdMyButton.Enabled = False
' Code to do whatever you would like here
' Yadda, yadda
End Sub
 
Back
Top