Microsoft Access VBA Macro Programming

(Tina Sui) #1

A Simple Use of the User Name


Now that you have the identity of the user entering your application, you can begin putting it
to good use.
The most basic question is “Should this user be in this application?” If they are not an
authorized user for this application (perhaps it’s someone who has come across it by accident
and wonders what it does), you need to deny them access and get them out as fast as possible.
An easy way to do this is to set up a single column table so each record holds a single user
name of authorized users. Call the table AuthorizedUsers and the single field UserName.
Populate the table with user names (including your own).
You can then use the following code:


Sub CheckUser()
Dim RcSet As Recordset
Set RcSet = CurrentDb.OpenRecordset _
("select * from AuthorizedUsers where UserName='" & ReturnUserName & "'")
If RcSet.RecordCount = 0 Then
MsgBox "You are not authorized to use this application", vbInformation
DoCmd.Quit
Else
MsgBox "Welcome to " & ReturnUserName & ",vbInformation"
End If
End Sub


The code creates aRecordsetobject called RcSet and opens the recordset as a query on
the AuthorizedUsers table, filtering where the UserName field equals the name returned by
theReturnUserNamefunction.
If theRecordCountproperty is zero, then an imposter has been detected and a message
box displays a suitable warning. The code then quits from the application preventing the user
from doing anything more.
If theRecordCountproperty is not zero, then a welcoming message box is displayed and
the application stays live.
You can obviously see that, by identifying the user immediately, this opens up a number of
interesting possibilities regarding how you control your application with different users. This
is discussed fully in Chapter 40.
When entering user names into the AuthorizedUsers table, you need to make sure they are
spelled correctly and correspond exactly to the user name string returned by the API call. My
own last name, Shepherd, has myriad spelling variations, and it can be extremely frustrating
for a valid user to be given the “unauthorized” message and kicked out of the application.
Fortunately, Access is not case-sensitive, so you do not need to worry about upper- and
lowercase in the strings.


Chapter 23: Getting the Login ID 281

Free download pdf