473,405 Members | 2,294 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Handler for multi Command Button, to make the code shorter

calaxan
12
Hi All...
I have 27 command buttons (it's alphabet) to get Employee Name based on First Letter and to display it on List Box.
Actually i got how to do it, but the code would be too long.
Could be somebody here can help me to make the code shorter. The code is like below:

Expand|Select|Wrap|Line Numbers
  1. Private Sub Command2_Click()
  2. Dim crSQL As String
  3.  
  4. crSQL = "SELECT EmpName FROM tblEmployee WHERE [EmpName] LIKE 'a*' "
  5. Me.lstEmpName.RowSource = crSQL
  6. Me.lstEmpName.Requery
  7.  
  8. End Sub
  9.  
  10. Private Sub Command3_Click()
  11. Dim crSQL As String
  12.  
  13. crSQL = "SELECT EmpName FROM tblEmployee WHERE [EmpName] LIKE 'b*' "
  14. Me.lstEmpName.RowSource = crSQL
  15. Me.lstEmpName.Requery
  16.  
  17. End Sub
  18.  
  19. Private Sub Command4_Click()
  20. Dim crSQL As String
  21.  
  22. crSQL = "SELECT EmpName FROM tblEmployee WHERE [EmpName] LIKE 'c*' "
  23. Me.lstEmpName.RowSource = crSQL
  24. Me.lstEmpName.Requery
  25.  
  26. End Sub
  27.  
Thanks for the help
Mar 10 '16 #1

✓ answered by Luk3r

You could turn your button code into a function and under each button click, add a global variable, set that global variable to the letter you want to be search in your SELECT statement, and replace the current letter within the SELECT statement with the global variable that you specified.

Function Code:
Expand|Select|Wrap|Line Numbers
  1. crSQL = "SELECT EmpName FROM tblEmployee WHERE [EmpName] LIKE '" & letterVariable & "*' "
  2. Me.lstEmpName.RowSource = crSQL
  3. Me.lstEmpName.Requery
  4.  
Global Variables:
Expand|Select|Wrap|Line Numbers
  1. Dim letterVariable As String
  2. Dim crSQL As String
Command Click:
Expand|Select|Wrap|Line Numbers
  1. letterVariable = "a"
  2. ##call the name of your function here##
  3.  

14 1193
Luk3r
300 256MB
You could turn your button code into a function and under each button click, add a global variable, set that global variable to the letter you want to be search in your SELECT statement, and replace the current letter within the SELECT statement with the global variable that you specified.

Function Code:
Expand|Select|Wrap|Line Numbers
  1. crSQL = "SELECT EmpName FROM tblEmployee WHERE [EmpName] LIKE '" & letterVariable & "*' "
  2. Me.lstEmpName.RowSource = crSQL
  3. Me.lstEmpName.Requery
  4.  
Global Variables:
Expand|Select|Wrap|Line Numbers
  1. Dim letterVariable As String
  2. Dim crSQL As String
Command Click:
Expand|Select|Wrap|Line Numbers
  1. letterVariable = "a"
  2. ##call the name of your function here##
  3.  
Mar 10 '16 #2
calaxan
12
Thanks Luk3r, it's help me.
Mar 12 '16 #3
calaxan
12
upgraded a lil bit:
Expand|Select|Wrap|Line Numbers
  1. Option Compare Database
  2. Dim iSQL As String
  3.  
  4. Private Sub Command7_Click()
  5.     GetEmpName ("m")
  6. End Sub
  7.  
  8. Function GetEmpName(myLetter As String)
  9.     iSQL = "SELECT EmpName FROM tblEmployee WHERE [EmpName] LIKE '" & myLetter & "*' "
  10.     Me.lstEmpName.RowSource = iSQL
  11.     Me.lstEmpName.Requery
  12. End Function
  13.  
Mar 12 '16 #4
Luk3r
300 256MB
Even better than my basic suggestion. Nice job!
Mar 14 '16 #5
NeoPa
32,556 Expert Mod 16PB
Let me start by directing your attention to Require Variable Declaration. It's a massive mistake to overlook this.

Then I can make a suggestion to reduce the code even further.

The .Requery isn't required as the control's data is repopulated once you change it. Also, the procedure should be a subroutine rather than a function.

Here's how you could do it to reduce the code further :
Expand|Select|Wrap|Line Numbers
  1. Option Compare Database
  2. Option Explicit
  3.  
  4. Private Sub Command1_Click()
  5.     Call GetEmpName("A")
  6. End Sub
  7.  
  8. ...
  9.  
  10. Private Sub Command26_Click()
  11.     Call GetEmpName("Z")
  12. End Sub
  13.  
  14. Private Sub GetEmpName(myLetter As String)
  15.     Me.lstEmpName.RowSource = Replace("SELECT [EmpName] " _
  16.                                     & "FROM   [tblEmployee] " _
  17.                                     & "WHERE  ([EmpName] LIKE '%L*')" _
  18.                                     , "%L", myLetter)
  19. End Sub
NB. I've marked Luk3r's post as Best Answer as it pointed the way to the solution.
Mar 15 '16 #6
calaxan
12
NeoPa...your code above is not working to me. I dont know why :)
Mar 15 '16 #7
PhilOfWalton
1,430 Expert 1GB
Slightly different approach.
I have an Option group called "FilterGrp" (with the 26 letters + "All". The OptionValue goes from 65 to 90 for A to Z and 91 for the "All".
I also have a textBox called "Filter" on the form.
The AfterUpdate of FilterGrp runs this

Expand|Select|Wrap|Line Numbers
  1. Function FilterType(Frm As Form)
  2.     On Error GoTo FilterType_Err
  3.  
  4.     With CodeContextObject
  5.         If (.FilterGrp = 91) Then
  6.             ' Set ShowFilter to "All"
  7.             Frm!ShowFilter = "All"
  8.             ' Set Filter to letter selected with []*
  9.             Frm!Filter = "*"          ' Changed from "[]*"
  10.         End If
  11.         If (.FilterGrp <> 91) Then
  12.             ' Set ShowFilter to letter selected
  13.             Frm!ShowFilter = GetLetter(Frm)
  14.             ' Set Filter to letter selected with []*
  15.             Frm!Filter = "[" & Frm!ShowFilter & "]*"
  16.         End If
  17.  
  18.         ' FormType
  19.         On Error GoTo FilterType_Exit
  20.  
  21.         DoCmd.GoToControl "NamePickList"        ' Move the focus
  22.         Call SurNameFilter(Frm)
  23.     End With
  24.  
  25. FilterType_Exit:
  26.     Exit Function
  27.  
  28. FilterType_Err:
  29.     MsgBox Err.Description
  30.     Resume FilterType_Exit
  31.  
  32. End Function
  33.  
This routine copes with foreign letters

Expand|Select|Wrap|Line Numbers
  1. Function GetLetter(Frm As Form) As String    ' Returns the corresponding letter for the button pressed
  2.                                   ' Accented characters mapped to the same char
  3.                                   ' without the accent
  4.     Dim iNum As Integer
  5.     Dim stRetVal As String
  6.  
  7.     iNum% = Frm!FilterGrp
  8.     If iNum% = 91 Then
  9.         GetLetter = ""
  10.     Else
  11.         stRetVal$ = Chr$(iNum%)
  12.  
  13.         ' Map accented and other special chars to a button
  14.  
  15.         Select Case stRetVal$
  16.             Case "a":
  17.                 stRetVal$ = stRetVal$ + "ÀÁÂÃÄ"
  18.             Case "c":
  19.                 stRetVal$ = stRetVal$ + "Ç"
  20.             Case "e":
  21.                 stRetVal$ = stRetVal$ + "ÈÉÊË"
  22.             Case "i":
  23.                 stRetVal$ = stRetVal$ + "ÌÍÎÏ"
  24.             Case "n":
  25.                 stRetVal$ = stRetVal$ + "Ñ"
  26.             Case "o":
  27.                 stRetVal$ = stRetVal$ + "ÒÓÔÕÖ"
  28.             Case "s":
  29.                 stRetVal$ = stRetVal$ + "Š"         ' This is S hacek
  30.             Case "u":
  31.                 stRetVal$ = stRetVal$ + "ÙÚÛÜ"
  32.             Case "y":
  33.                 stRetVal$ = stRetVal$ + "Ýÿ"
  34.             Case "z":
  35.                 stRetVal$ = stRetVal$ + "ZÆØÅ"
  36.         End Select
  37.  
  38.         GetLetter = stRetVal$
  39.     End If
  40.  
  41. End Function
  42.  
The Rowsource for the filtered names is

Expand|Select|Wrap|Line Numbers
  1. SELECT DISTINCTROW Member.MemSurName, Member.MemFirstName, Member.MemberID
  2. WHERE Member.MemSurName) Like [screen].[activeform]![Filter])
  3. ORDER BY Member.MemSurName, Member.MemFirstName;
  4.  
Phil
Mar 15 '16 #8
NeoPa
32,556 Expert Mod 16PB
Calaxan:
NeoPa...your code above is not working to me. I dont know why :)
Well, I can't see your system so it'll be hard for me to work out why it's not working for you.

Why don't you start by giving me some information about what happens when it doesn't work? An error message is good if you have one. Any clues are good really. Nothing at all isn't something I can work with easily.
Mar 16 '16 #9
NeoPa
32,556 Expert Mod 16PB
@Phil.
Would you like to give a reason why someone may want to use your approach in preference to the others suggested which seem clearly more straightforward. Sometimes complexity is necessary, but you give nothing to suggest why this might be the case here. The original question gave no indication that special keys or values are required, so that can't be it.
Mar 16 '16 #10
PhilOfWalton
1,430 Expert 1GB
Main reason is that you are using an option group to establish which letter has been selected rather than having a Sub firing on each letter. Again very simple to extend if you want to filter on numbers as well as letters.
The Function GetLetter is only useful if you are dealing with foreign names though I certainly have come across the odd Norwegian and French names with odd accents on them, and if they have been entered in the database with the accent, this routine should find them.
In addition the "All" option removes the filter so that the listbox shows everyone.

Phil
Mar 16 '16 #11
NeoPa
32,556 Expert Mod 16PB
PhilofWalton:
Main reason is that you are using an option group to establish which letter has been selected rather than having a Sub firing on each letter.
That's confusing. My code, and when I refer to mine I also include Luk3r's as well as it's fundamentally very similar, uses what the OP indicated they had, which was a bunch of different Command Buttons. I'm not sure where you believe the Option Groups come in.

Having said all that, your suggestion is an alternative and that's always good to see. I'm sure those on the look out for help in such an area will look at both and choose the approach that best suits their own requirements.

Having decided to read your suggestion in more detail it seems that :
  1. It's air-code. This isn't too much of a problem but please be careful to remove obvious erros like where the parentheses are so they match up. I post a lot of air-code myself, but I'm always careful to check it thoroughly first.
  2. It offers a clever approach to handling non-standard versions of the main letters. I expect this is the real reason for posting in the first place. It doesn't match the question of this thread, but is worth including for any that need that extra flexibility.

Overall it's worth posting. I would only say that being clearer about what it is can be particularly helpful when it's beyond the limited scope of the thread.

It seems you're new here. Already I can tell you have much to offer. Please don't let my advisory comments put you off. You're very welcome at Bytes.com and I look forward to seeing more of your contributions.
Mar 16 '16 #12
PhilOfWalton
1,430 Expert 1GB
Sorry, I didn't make myself clear. The 26 letters + "All" are toggle buttons on the option group (FilterFrp), and there is no code attached to the 27 toggle buttons. Depending on which letter is pressed, the value of the FilterGrp changes between 65 for an "A" to 91 for an "All". Note Toggle Buttons can only have numeric values, hence the need to use the ASCII value of the letter.
The code (not air code) runs on the AfterUpdate of the FilterGrp (ie a letter key has been pressed).
Basically that creates the appropriate letter for the "WHERE" clause for the query on which the list box of Employee names is based.
I fully accept that handling non standard letters is overkill.
Mar 16 '16 #13
NeoPa
32,556 Expert Mod 16PB
Ah. That's clearer now. I took the first 'you' in your explanation to mean 'you', but essentially I should have read it as 'one'. Thus, referring to your approach rather than ours.

That's probably a better way to approach it, but that's advice to the OP about a better question as opposed to their actual one. Worth making the point, I agree.

@Calaxan.
You may want to give consideration to Phil's advice on how better to design the interface for what you want to achieve. It makes good sense to use an Option Group instead of a whole bunch of separate Command Buttons. It also makes the code tidier and easier to maintain. The AfterUpdate event handler is a single point of entry.
Mar 17 '16 #14
calaxan
12
Thanks to PhilOfWalton and NeoPa, your sharing is opening my mind to have another option of my previous code.

Best Regards,
Access Newbie :)
Mar 17 '16 #15

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Sam | last post by:
Trying to change the visible property on a command button (access97) based on a record felid on the form. The felid is a check box felid and I am trying to make the button disappear with the...
13
by: Darrell Wesley | last post by:
In VB6 all you needed to do was set the name of the command button to True like: cmdGo = True but this does not work in vb.net Is there a code sample that shows how to do this?
14
by: Kevin | last post by:
A couple of easy questions here hopefully. I've been working on two different database projects which make use of multiple forms. 1. Where's the best/recommended placement for command buttons...
2
by: Senthil | last post by:
Hi All I need to create an Excel report and create a command button and have to run a macro on the click event that will print all the pages in the Excel workbook. I am able to create the report...
0
by: mesadobes | last post by:
I am very new to visual basic. Actually, I have no clue what I'm doing! But I know what I want to do. I am trying to learn as I go... How do I create a command button that when clicked will...
3
by: WiscCard | last post by:
This seems simple enough, but I am having problems. I have a table of customer information. I have a form with various combo boxes displaying unique customer information (in this case, zone and...
3
by: skanemupp | last post by:
is there anyway to make this shorter? i hate having these big blocks of similar-looking code, very unaesthetic. maybe doesnt matter good-code-wise? anyway can i make some function that makes this...
3
by: webster5u | last post by:
Hi, i have a question about JavaScript. When we click a submit button from the form with multi-submit button. Can JavaScript detect which submit button has been submit? I make a form with 3 submit...
3
by: sjstevens9 | last post by:
I'm trying to put a button on a form that will change the status field of a record from "0" to "1" and then save the record. Is this possible and what is the best way to do it? The status will be...
1
by: Tesplund | last post by:
I am using VB to create a code that will save a copy, send it via outlook then delete the copy it saved. I want this to be via command button but am not picky as long as it's as easy as the comman...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.