Topic: “A Simple Numeric Entry Keypad”

17
1 Human Factors Engineering Short Course 2016 Creating User Interface Prototypes with Microsoft Visual Basic for Applications 3:55 pm – 4:55 pm, Wednesday, July 27, 2016 Topic: “A Simple Numeric Entry Keypad” Lecture Notes and Additional Resources at <http://www.umich.edu/~driving/shortcourse/vba> Te-Ping Kang [email protected] Dr. Paul Green [email protected] Dr. Brian T. Lin [email protected]

Transcript of Topic: “A Simple Numeric Entry Keypad”

Page 1: Topic: “A Simple Numeric Entry Keypad”

1

Human Factors Engineering Short Course 2016

Creating User Interface Prototypes with Microsoft Visual Basic for Applications

3:55 pm – 4:55 pm, Wednesday, July 27, 2016

Topic: “A Simple Numeric Entry Keypad”

Lecture Notes and Additional Resources at <http://www.umich.edu/~driving/shortcourse/vba>

Te-Ping Kang [email protected] Dr. Paul Green [email protected] Dr. Brian T. Lin [email protected]

Page 2: Topic: “A Simple Numeric Entry Keypad”

2

A Simple Numeric Entry Keypad using Microsoft Visual Basic for Applications

0. Demo the final interface to the class 1. Open Microsoft Excel 2. Open VBA for Excel via Macro editor Click on View→ View Macros

3. In the Macro window, type a name and hit Create to Enter Visual Basic Editor. (or press ALT+F11 to access Visual Basic Editor directly)

Page 3: Topic: “A Simple Numeric Entry Keypad”

3

4. The Visual Basic Editor screen will showed immediately, and hit Close to close the Module1 window

5. Insert a UserForm

Page 4: Topic: “A Simple Numeric Entry Keypad”

4

6. The UserForm a. Properties The (Name) Property is the name of the form when programming. The Caption is the heading seen by the user. b. Toolbox Contains common application controls such as labels, textboxes, and command buttons.

Page 5: Topic: “A Simple Numeric Entry Keypad”

5

7. Creating a KeyPad User Interface a. Insert CommandButtons for the keys b. Change their Properties

i. Two CommandButtons are shown, the top one is a default button, and the bottom one has its Name changed to cmdKey1, and the Caption to 1.)

ii. BackColor changes the background color of the key (optional) iii. Font changes type, style, size, and effects (optional) iv. ForeColor changes font color (optional)

c. Create keys for the numbers 0 through 9, and a Clear key. Manually resize the keys if desired. Use the following naming convention: cmdKey[Keyname]. (Tip: Use the Format menu to arrange and align multiple CommandButtons.)

Page 6: Topic: “A Simple Numeric Entry Keypad”

6

d. Insert a TextBox to display the numbers entered. Change its Name to txtDisplay, and change the Font and TextAlign Properties if desired.

8. Making the KeyPad work: The Underlying Code

a. Open the Code Window

Page 7: Topic: “A Simple Numeric Entry Keypad”

7

b. The Code Window Layout i. Object box contains a list of each control added (ex:CommandButtons) ii. Procedures box contains options specific to each control (ex: CommandButton Click event) [The Object Box] [The Procedures/Event Box]

[The Code Area]

c. Connecting KeyPresses to the Display

i. One-by-one, select each Key from the Object Box. Or you can double click the command keys in the window to add them. The default Procedure (Click) will be used.

Page 8: Topic: “A Simple Numeric Entry Keypad”

8

ii. Each Key has a click event, which is executed when the Key is clicked with the mouse. To have each key add a number to the display, add the following code within each event:

txtDisplay.Text = txtDisplay.Text + “[Key]” where [Key] is the corresponding Key clicked. iii. The Clear key will simply clear the display. txtDisplay.Text = “”

Page 9: Topic: “A Simple Numeric Entry Keypad”

9

9. To use the KeyPad, press F5 or Run/Run Sub to review the function of the Keypad

10. Add more functions - "backspace"

a. Repeat step 6, create a CommandButton for backspace

b. Double-click on the backspace CommandButton, and add the following code: txtDisplay.Text = Left$(txtDisplay.Text, Len(txtDisplay.Text) - 1)

txtDisplay.SelStart = Len(txtDisplay.Text) This is an example of mixing VBA and Excel native formulas. While VBA is responsible for the click event, the excel formula deals with the logic of backspace action.

c. Press F5 or Run/Run Sub to review the function of the calculator

Page 10: Topic: “A Simple Numeric Entry Keypad”

10

Optional Features 1. Add decimal point feature.

a. Add a decimal point CommandButton, change the name to CmdKeyDecimal.

b. Double click the button to add the following codes:

Dim pos As Integer pos = InStr(txtDisplay.Text, ".")

If pos = 0 Then txtDisplay.Text = txtDisplay.Text + "." End If

This is an example of using the IF, END IF clause in VBA. The InStr function will search how many decimal points were shown in the txtDisplay box. If there is no decimal points being found (pos = 0), Then add a decimal point at the end of the txtDisplay box.

Page 11: Topic: “A Simple Numeric Entry Keypad”

11

2. Add Keystroke Record Feature a. Add the following codes at the very beginning of the file:

Private targetFile As String Private RecordColumn As Integer

These are Global Variables that can be accessed anywhere in the code.

b. Add the following code after the global variables, or wherever blank lines between two subs.

Private Function RecordKeystroke(Key As String)

Windows(targetFile).Activate Worksheets(1).Activate Cells(RecordColumn, "A") = Key RecordColumn = RecordColumn + 1

End Function

Private Sub UserForm_Activate() targetFile = "[Your Excel File Name]" RecordColumn = 1 End Sub Change the [Your Excel File Name] part to the name of your current excel file name. For example, if your file name is vbademo.xlsm, please enter

targetFile = “vbademo.xlsm”

c. Using the RecordKeyStroke Function.

Now we need to put the function into the click actions to trigger it. For example, if we want to enable the function of recording Key 0, put the following code into CmdKey0_Click() action:

RecordKeystroke ("0") Repeat the same process, insert the following code into CmdKey1_Click() action. RecordKeystroke ("1")

Page 12: Topic: “A Simple Numeric Entry Keypad”

12

d. Press F5 to run the sub, now when you pressing 0 and 1, you should able to see the keystrokes being recorded on the excel file.

Global Variables

Keystroke function

Your excel file name

Add function to existing click actions

Page 13: Topic: “A Simple Numeric Entry Keypad”

13

3. Add Basic Calculator Feature a. add 5 CommandButtons and change the names and captions as follows,

Name Caption CmdKeyAdd + CmdKeySubtract - CmdKeyMultply * CmdKeyDivide / CmdKeyEnter =

b. Add two lines of code at the very beginning of the code area: Private op, prefix As String

Private inputMode As Boolean

Page 14: Topic: “A Simple Numeric Entry Keypad”

14

These two lines of code create multiple global variables for this form, which means that they can be accessed anywhere within the UserForm.

c. Double click on all five CommandButtons to create Click actions for all five buttons.Add the following codes for the four operator click actions

op = "[Key]" prefix = txtDisplay.Text txtDisplay.Text = ""

[Key] should be the same as the operator, for example, in CmdKeyAdd_Click() sub, add:

op = “+” at the first line. Finish all four operators.

d. Add the following codes for the Enter CommandButton Click action: Dim var1, var2 As Double var2 = txtDisplay.Text If prefix = "" Then var1 = 0 Else var1 = prefix End If inputMode = True Select Case op Case "+" txtDisplay.Text = var1 + var2 Case "-" txtDisplay.Text = var1 - var2 Case "*" txtDisplay.Text = var1 * var2 Case "/" If var2 = 0 Then MsgBox "Cannot divide by zero" inputMode = False Else txtDisplay.Text = var1 / var2 End If

End Select The first If, Else clause checks if the txtDisplay is empty, and converts the number to zero. The inputMode is a global variable Boolean value, checking if the user is trying

Page 15: Topic: “A Simple Numeric Entry Keypad”

15

to input a value, or just finished a calculation. The Select Case clause checks what kind of operator is being sent and what kind of calculation should be worked on. Please note that in the divide part, we need to include a divide by zero check to prevent overflow.

e. Finally, we need to add a function to check if the calculation has been finished. For example, if we just finished a 3 + 2 = 5 calculation, the next key-press should clear the current number and start a new calculation. Add the following code at the end of the code area.

Private Function CheckInputMode()

If inputMode = True Then inputMode = False txtDisplay.Text = "" prefix = "" End If

End Function This is an example of adding a standalone function that will be executed by every key the user pressed. The function will reset the number from the previous calculation, and also reset the inputMode flag.

f. Finally, Add the following code to the first line of all 9 number keys, the decimal, and backspace click action:

CheckInputMode For example, the CmdKey1_Click() sub should look like:

Private Sub cmdKey1_Click() CheckInputMode txtDisplay.Text = txtDisplay.Text + "1"

End Sub

g. Press F5 or Run/Run Sub to review the function of the calculator

Page 16: Topic: “A Simple Numeric Entry Keypad”

16

End of Demo Some Useful References on line Visual Basic Tutorial: How To Make A GUI (graphical user interface) - codecall.net (for calculator) http://www.youtube.com/watch?v=6enJdcRC1dk (other items on Youtube as well) books Berger, N., Arent, M., Arnowitz, J., and Sampson, F. (2009). Effective Prototyping with Excel, San Francisco, CA: Morgan Kaufmann. MacDonald, M. (2002). User Interfaces in VB.NET: Windows Forms and Custom Controls, New York, NY: Apress. Add Sound to Button Clicks

a. Scroll to the top of the user form code area and add at the very beginning the following code: #If Win64 Then Private Declare PtrSafe Function sndPlaySound32 Lib “winmm.dll” Alias “sndPlaySoundA”(ByVal lpszSoundName As String, ByVal uFlags As Long) As Long #Else Private Declare Function sndPlaySound32 Lib “winmm.dll” Alias “sndPlaySoundA”(ByVal lpszSoundName As String, ByVal uFlags As Long) As Long #End If This code instructs the program to do two things. First, the #If…#Else…#End If block tells the program to determine whether the current system is running a 32-bit or 64-bit version of Windows. Based on this, either the first block of code (between the #If…#Else statements) or the second block of code (between the #Else…#End If statements) will run; both of these blocks of code tell the program, essentially, to make the function sndPlaySound32 usable in the current user form. This is important, as sndPlaySound32 is the method by which sounds are played.

Page 17: Topic: “A Simple Numeric Entry Keypad”

17

b. Add to the beginning of the Sub block of each button the following code: If Application.CanPlaySounds Then Call sndPlaySound32(“C:\Windows\Media\Windows Navigation Start.wav”, &H1) End If Remember that the names of Sub blocks of buttons end with the sequence of characters “_Click()”, without the quotations. This code will first check if the program can play sounds, and, if it can, will then call sndPlaySound32, giving it the full path to the .wav file named “Windows Navigation Start.wav”. The program will navigate to the specified path to find the .wav file and attempt to play it when the button is clicked. When this code is added to the beginning of the Sub blocks of each button, every button will attempt to play this sound when it is clicked.

c. Press F5 or Run/Run Sub to check and see if the sound plays correctly. d. Note that the code in step (b) will play the same sound for each button. If it is

desired to play different sounds for different buttons, then it is only necessary to change the underlined portion of the code in part (b) with the full path of the new sound file. However, be aware that only .wav files will work in VBA. Further reading: Playing a Sound in VBA—Pearson Software Consulting http://www.cpearson.com/excel/PlaySound.aspx Declare Statement—Microsoft Developer Network https://msdn.microsoft.com/en-us/library/office/gg278581.aspx