<body><script type="text/javascript"> function setAttributeOnload(object, attribute, val) { if(window.addEventListener) { window.addEventListener("load", function(){ object[attribute] = val; }, false); } else { window.attachEvent('onload', function(){ object[attribute] = val; }); } } </script> <iframe src="http://www.blogger.com/navbar.g?targetBlogID=34083602&amp;blogName=LEARN+MS-ACCESS+TIPS+AND+TRICKS&amp;publishMode=PUBLISH_MODE_FTP&amp;navbarType=BLUE&amp;layoutType=CLASSIC&amp;searchRoot=http%3A%2F%2Fblogsearch.google.com%2F&amp;blogLocale=en_US&amp;homepageUrl=http%3A%2F%2Fwww.msaccesstips.com%2F" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" height="30px" width="100%" id="navbar-iframe" allowtransparency="true" title="Blogger Navigation and Search"></iframe> <div></div>
www.msaccesstips.com

LEARN MS-ACCESS TIPS AND TRICKS


International Response Fund

LEARN MS-ACCESS TIPS AND TRICKS

↑ Grab this Headline Animator

Your Ad Here
Friday, March 28, 2008

Double-Action Command Button

Double-Action doesn't mean that with one Click you can execute two different procedures. For that matter you can do several things at one click. Here, the emphasis is on programing the same Command Button for doing two different Actions i.e. when the Button is Clicked a second time it will execute a different action than it did for the first one.


To make the point more clear, let us look into a real world example. When the user opens a Data Editing Screen we want the screen to be kept locked for safety of the data and to prevent users changing the field values accidently.


But, when it is time to make some changes in one or more fields on the current record the user will Click the Command Button to unlock the Form for editing.
After editing, the User will Click the same Button again to lock the screen.


Let us try an Example. But, before starting with the design task let us note down the above points with more specifics so that you will have a general idea what we are trying to do, when we proceed with the implementation steps.


Consider the Requirements


(a) When the Form is open for the first time, or when moved from one record to the other, the Form must be Locked from editing. Why when moving from one record to the other? Well, the User clicked the Button to unlock the Form for editing, but he forgot or didn’t bother to click a second time to lock the Form. So we will apply an automatic Lock when she moves into another record.


(b) When the user goes for adding a New Record the Form is fully open for keying in values and our Double-Action Command Button will be in a disabled state.


(c) When the user Clicks the Double-Action Command Button (as we call it now) for the first time, unlock the Form for editing.


(d) When she Clicks the same button a second time, lock the form again for safety of data.


The only question at this point is that how do we determine which click is for what, and if the user repeats the clicks several times, then what happens? It is very simple, read on.


Design Task

  1. Open one of your existing Projects with a Data Editing Screen already available in it.



  2. Create a Command Button at the Footer of the Form.



  3. Click on the Command Button to select it, if it is not already in a selected state, display the Property Sheet (View -- > Properties).



  4. Change the Name Property to cmdEdit.



  5. Change the Caption Property (very important) Value to Edit.



  6. To take care of the points that we have noted at (a). and (b). above, display the VBA Module of the Form (View --> Code) copy and paste the following Code into the Module.




  7. Private Sub Form_Current()
    If Me.NewRecord Then
    With Me
    .cmdEdit.Caption = "Edit"
    .cmdEdit.ForeColor = 0
    .cmdEdit.FontBold = False
    .AllowEdits = True
    .cmdEdit.Enabled = False
    End With
    Else
    With Me
    .AllowEdits = False
    .cmdEdit.Caption = "Edit"
    .cmdEdit.ForeColor = 0
    .cmdEdit.FontBold = False
    .cmdEdit.Enabled = True
    End With
    End If

    End Sub



    The above code will take care of the New Record entry event as well as applying the automatic Lock when the User didn’t Click the Command Button to Lock the Form directly.


    Now we can concentrate on the Button Click part i.e. (c) and (d) points given above. Here, we have to check for the sate of the Button when Clicked by the User. The trick is checking the Caption Value of the Button and decide what is the user’s intentions and set the Form Locked or Unlocked state. At every click on the Button we will change the Caption Value to Edit or Lock interchangably.


    • If the Caption Value was Edit when the user clicked the button then he/she wants to edit values on the Form.



    • If the Caption Value was Lock, then the user wants to lock the Form after editing the data.



  8. The following Code will do the trick. Copy and paste the VBA Code into the Form’s Module and save the Form.



Private Sub cmdEdit_Click()
Dim cap As String
cap = Me.cmdEdit.Caption
Select Case cap
Case "Edit"
With Me
.AllowEdits = True
.cmdEdit.Caption = "Lock"
.cmdEdit.ForeColor = 128
.cmdEdit.FontBold = True
.Refresh
End With
Case "Lock"
With Me
.AllowEdits = False
.cmdEdit.Caption = "Edit"
.cmdEdit.ForeColor = 0
.cmdEdit.FontBold = False
.Refresh
End With
End Select
End Sub


Experiment with your design and check whether it works every time correctly as expected.


If any suggestions for improvement or found that it didn’t work the way you expected it then please post them in comments.



Msgbox with Options Menu
Who Changed the Data
Progress Counter
Progress Bar on Form
Progress Meter

Labels:

6 Comments:

Blogger JustMe said…

Mr. Pillai,

A double action command button is very helpful. Thank you for this post.

I was able to get your code to run on MS Access 2003 but can't seem to adapt it to my specific need. Can you help me?
I am generating a document number using a command button and visual basic. The code is working.
The document number starts with three letters, which are always the same (ABC). The letters are followed by a six digit number (must be 6 digits), then the initials of the person adding the document (varies from 2 to 4 letters), and if the document is a revision of an existing document, then ".Rev" followed by the revision number.
The first action command of the "Generate Document Number" button is twofold:
If the document is a revision, the user provides the original document number, the initials of the person adding the document (from a drop down box), and the revision number. The document number is generated by concatenating the provided document number & person's initials & ".Rev" & the revision number. The document number may look like ABC000044JB.Rev1
If the document is not a revision (Me.RevisionNumber = "None"), the user supplies the initials of the person adding the document, then I loop through each MID(Me.DocumentNumber 4, 6) (While Not EOF) and find the largest of the six digit numbers, maxnum, (using EVAL). That number is incremented by one. The original document number is then [Document Number:] = "ABC" & maxnum + 1 & the initials of the person adding the document. It may look like ABC000045JB
Trouble:
The problem with this is when the user generates a document number then needs to change either the initials or revision number. When they make their change and use the "Generate Document Number" command button again, it increments the current document number and replaces an earlier document number with the one just changed. So the new number would be ABC000046KD or ABC000046JB.Rev1 but a document number previously entered has been replaced by ABC000045JB. That messes up our library.
I am trying to use your code to resolve this problem.
Once the document number is generated, I need to make Left(DocumentNumber, 9) so that it cannot be changed (in any record) and the second action command of the "Generate Document Number" button (caption now should be "Update Document Number") so that if a user changes either the initials or revision number, it will keep Left(DocumentNumber, 9) and concatenate the initials & ".Rev" & revision number. (If things get bad for the user, I have a "delete the current record" button.)
I would like to make it so that Left(DocumentNumber, 9) of the Document Number field is .AllowEdits = False but the rest of the document number and the rest of the form can be edited.

Can you help me with this? Or perhaps point me in the right direction?

Thank you, I very much appreciate your time and expertise.

/R,
Jan

April 09, 2008 11:25 PM  
Blogger a.p.r. pillai said…

Sorry for the delay.

Since, part of the same Field cannot be locked from editing you can make the Document Number into two segments, first 9 characters in one field and the rest in second. On the table you can define the Document Number Fields as Primary Key using both segments together. On the Form lock the first segment field (Me.FirstSegment.Locked = True) so that it remains safe. After editing the second segment, on the Lost Focus Event of the field, save the current record’s Form Bookmark (strBkmk = Me.Bookmark) in a variable and scan through the recordset (.recordsetclone of the Form) with the modified Document Number. If a match is found within the Recordsetclone and the Bookmark doesn’t match with the current Form Bookmark then you found another record with the same number and warn the User about the wrong change. You can put back the old value of the second segment by referring the .OldValue property in Code, Me.SecondSegment.Value = Me.SecondSegment.OldValue and put back the Focus on the second Segment again.

For resetting the focus back to the same field, you have to define a variable at the Form’s Global level, say Err_Flag as Boolean. Check the status of this variable on the Got_Focus event of the next field in the Tab Index order, if it found set with the value True then put the focus back to the second segment field (me.secondsegment.setfocus = true) so that the user is forced to have a re-look on the change of number.

This may not be the 100% correct solution to your problem but I hope it will help you to think differently.

Regards,

April 11, 2008 10:18 AM  
Blogger a.p.r. pillai said…

I had a re-look at the problem that you have presented and created a small sample database with test routines. I hope this will help you to find answers to most of your Queries. You may download this database in Zipped form by following this Link: http://www.msaccesstips.com/downloads/2008/04/DocNo.zip.
You may modify the code further to refine them against User made errors like very large version number or irrelevant Initials and so on.

1. On the current event of the Form the Document Number can be divided into 3 segments (first 9 characters, Initials & Revision Number, while maintaining the original Document Number in one field) and display them in 3 different unbound Text Boxes. The Original Document in full can be displayed in the Field in a locked
condition. The first segment Text Box also must be kept locked.

2. When the User makes changes to the Initial and Revision Text Boxes, log that event and enable the 'Revision Update' Command Button so that the user can click to generate a new Version of the existing Document. Keep the Command Button disabled till the user makes some changes to these two text boxes.

3. a) Assemble Document Number using all the three segments edited by the User and check in the recordsetclone whether a record already exists with the same number. If so display a warning message and quit the procedure. If the Document Number is defined as primary Key Field then MS-Access will automatically take care of this step.

b) Add a new Record in the Recordsetclone using the Document with New Version Number and copy other fields into it from the Form Fields.

c) Refresh the recordset to register the Bookmark of the new record added. Search for the same record in the recordsetclone with the Document Number and use the Bookmark of the recordsetclone to set the Bookmark of the Form resulting the new Record become Current on the Form.

4. When the User attempts to add a New Document we can generate the new Document Number by using the maximum Number available in the table + 1 in the Before_Insert Event Procedure. Maximum value available in the table can be obtained using a Total Query (SELECT Max(Val(Mld([DQCNQ],4,6))) AS [MAX] FROM Tablel;).

5. Read the value into the program using Dlookup() Function. The New Number will be created and recorded only when the user makes an entry of a character in any of the Fields on the Form.

The Command Button's usage comes only once when attempting to create a new Version of the Existing Document.

April 14, 2008 10:19 PM  
Blogger magmike said…

I had previously used two command buttons to reach the same goal, one on top of the other - one hidden, one not. I was glad to see your trick - which more than anything, helped me think differently.

However, I put it to the test, and while it works, it seems to take longer to process, where the two button version happens instantly. I'll include my code, so you can tell me if something I've done is causing this.

Thanks for your help!

Private Sub Edit_Click()
Dim cap As String
cap = Me.Edit.Caption
Select Case cap
Case "Edit List"
Forms!ProspectForm!ContactList2b.Form!ContactSelect.Visible = True
With Me
.DeleteContacts.Visible = True
.Edit.Caption = "Edit Off"
.Refresh
End With
Case "Edit Off"
Forms!ProspectForm!ContactList2b.Form!ContactSelect.Visible = False
With Me
.DeleteContacts.Visible = False
.Edit.Caption = "Edit List"
.Refresh
End With
End Select
End Sub

December 23, 2008 7:29 PM  
Blogger a.p.r. pillai said…

Probably the Font Color and Style change causes the delay.

Regards

December 25, 2008 6:46 PM  
Blogger Steve said…

I have been searching all over the web for a solution like this, and your double click command button has made life so much easier. I want to be able to lock all my fields, except one though, as I still want to include a surname search option. Is there something I can add in to your code to allow this. Many thanks

January 29, 2009 3:24 PM  

Post a Comment

Note:Comments subject to Review by Blog Author before displaying.

Links to this post:

Create a Link

<< Home


Creative Commons License
Learn MS-Access Tips and Tricks by msaccesstips.com is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 2.5 India License.



This Page is best viewed with 1280 x 1024 Resolution

   FEATURED LINKS
SITEMAP
Command Button Animation
3D Headings on Forms
MsgBox & Office Assistant
Reminder Ticker
MS-Access & E-Mails
Automated E-Mail Alerts
MsgBox with Options Menu
Colorful Command Buttons
Configure Lotus Notes
Alerts through Network
Running this site has become a costly affair as the revenue from Ads is not sufficient to support it. If you find these pages informative & useful and would like to extend a helping hand, then please do it here.





Link Back to us with this Button

Learn MS-Access

Copy and Paste this HTML Code in your Webpage


Add to Technorati Favorites

Programming Blogs - Blog Catalog Blog Directory
Powered by FeedBurner
Add to Google

Software
Computers blogs
TopOfBlogs




AddMe - Search Engine Optimization Submit Your Site Free!
Go BlogZ Ave Blogs
eBlogzilla Changing LINKS
LS Blogs Blogarama
blog search directory BlogUniverse
Find Blogs in Directory RSS Directory
blogskinny.com ShowcaseBlogs.com
Amfibi

Search Engine Optimization and SEO Tools
Dmegs Web Directory Takeaway for Sale Businesses For Sale
Free Submission Directory Free site submission

Free Listing
 





Free Page Rank Checker

AddThis Social Bookmark Button

Enter your email address:

Delivered by FeedBurner



Top Blogs


Microsoft Access is the Jewell among MS-Office suite of Applications. Its Security features are excellent and works fine in Network environment. MS-Access can link/upload data from any Data Source. Applications that you design should be user-friendly and visually pleasing too. Here I would like to share my experience in Microsoft Access Programming with you and I am sure that you will find them interesting too.

My Photo
Name: Ramachandran Pillai
Location: Cochin, India

I am not an Access Guru and not through MS-Access yet. More to learn and I don’t think that aspect has any end because others have their own style of using this tool. We can learn lot more tricks, other than what we already know, from others too. My programming skills in COBOL, BASIC, Turbo-C, dBase, FoxPro, Visual Basic & Basic HTML attained through self-learning. I wrote my first COBOL Program in 1975 for ICL1901, 3rd Generation Main Frame Computer. Worked as a Computer Operator (NCR VRX8555 Mainframe Machine upto 1990) with M/s. Y.B.A. Kanoo, Saudi Arabia. Started using MS-Access Ver.2 in 1996, when dBase III+ and Foxbase (later version Foxpro) were my favorite DBMS. During Last 13 Year period I have developed more than 45 In-House Applications (medium & small) under MS-Access for our Organization, a leading Automotive Company in Oman. All the Applications are fully Secured and runs under Windows Network. It is my pleasure to share my experience with others. Anything interesting that you would like to share with me, please do. My E-mail Address: aprpillai@msaccesstips.com


If you need a Demo of any of the Topic explained here, send me an E-mail to: aprpillai@msaccesstips.com
with the Topic Description, I shall try to send a sample database to you.


Access Tips | Email | Reports | Report Tricks | Graphs | Forms | Menus | Animation | Security | Internet | How TOs | Linking | Query | Progress Meter | Alerts | Process Tips | Access Functions |




Site Designed by:www.msaccesstips.com