Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Creating User-Account with VBA

Introduction.

To create a Microsoft Access user account in the Workgroup Information File .mdw, navigate to:
Tools → Security → User and Group Accounts → User Name tab.
There, provide a unique User Name and a Personal ID to create a new user account.

We discussed this procedure earlier in the Security Main Menu. The User IDs, Personal IDs, Workgroups, and Passwords are stored in the Workgroup Information File, a database with the .mdw extension. The default file used by Microsoft Access is SYSTEM.MDW.

Access privileges for database objects are stored within the database itself. Together, these two components form the combination lock of Access security:

  • The User ID and Personal ID stored in the Workgroup Information File act as the key, and

  • The object-level access rights stored within the database serve as the lock.

A user gains access to specific objects only when the correct User ID, Password, and Personal ID are provided.

The Personal ID is a critical part of each user’s profile—it is required if you ever need to recreate a Workgroup Information File after the original one becomes corrupted or lost.

Only Administrators (members of the Admins Group with administrative privileges) have the authority to create and manage User and Group IDs.

Creating a User Account Manually.

First, let’s create a test user account manually. Follow the procedure given below to create a user account step by step.

User Name: JOHNSMITH (maximum 20 characters)

  • Personal ID: JS123456 (4 to 20 Alphanumeric characters)

Visit the link: Create MS-Access User Account for more details.

  1. Select Tools -> Security -> User and Group Accounts

  2. Click New in the Users Tab.

  3. Type JOHNSMITH in the Name control.

  4. Type JS123456 in the Personal ID control.

  5. Click OK to complete the procedure.

The Users Group.

By default, all user accounts are automatically added as members of the Users Group. If a user needs to belong to additional user groups, you must select the desired group name from the Available Groups list and add it to the Member Of list using the control on the right-hand side.

Now, let’s learn how to create a user account using VBA—excluding, for now, the step that assigns the user to a specific group. We’ll explore how to link users to groups later, after we cover how to create a group account with VBA.

Create a User Account with VBA.

The following VBA Code creates a User Account with the User Name: SMITHJOHN, with the Personal ID: SJ78901, and with an initial Password: SMITHJOHN:

Public Function CreateUsers()
'---------------------------------------------------------------------------------
'Author : a.p.r. pillai
'Date   : Feb-2010
'All Rights Reserved by www.msaccesstips.com
'Other Ref: http://www.msaccesstips.com/2006/11/create-msaccess-user-account/
'---------------------------------------------------------------------------------
Dim wsp As Workspace
Dim newUser As User, tempGrp As Group
Dim UsrName As String, PersonalID As String
Dim Password As String

On Error Resume Next

Set wsp = DBEngine.Workspaces(0)

    UsrName = "SMITHJOHN" ' 1 to 20 characters.
    PersonalID = "SJ78901" 'upto 4 to 20 alphaumeric characters
    Password = "SMITHJOHN" 'upto 14 characters except NULL

'Create User Account with personalID
   Set newUser = wsp.CreateUser(UsrName, PersonalID, Password)
   wsp.Users.Append newUser

   If Err = 3390 Then
      MsgBox "User Name : " & UsrName & vbCr & vbCr & "User PID    : " & PersonalID & vbCr & vbCr & "Account Name already Exists..! "
      Err.Clear
      Exit Function
   End If
   wsp.Users.Refresh

'Users Group must be created and joined the
'User to it. When created manually this step
'(for Users Group)is done automatically.
   With wsp
     Set tempGrp = .Users(UsrName).CreateGroup("Users")
         .Users(UsrName).Groups.Append tempGrp
         .Users.Refresh
   End With

End Function

When we create a User-ID, we can only set a password for the User manually.  After opening a new MS-Access Application window, select the Menu Options Tools ->Security ->User and Group Accounts ->, log in without a password, select the Change Logon Password Tab of the Dialog Control, and set a new password.

  1. Copy and paste the above Code into a Standard Module and save it.

  2. Click somewhere in the middle of the Code and press F5 to run the Code and create the User Account in the active Workgroup Information File.

  3. Select Tools - ->Security- ->User and Group Accounts and check for the User Name SMITHJOHN on the list.

The UserNames are in alphabetical order.

Check for a Particular UserName with VBA.

We can check for the presence of a particular UserName in the active Workgroup Information File with the following VBA Code:

Public Function Check4UserAccount(ByVal strUsrName As String) As Boolean
'------------------------------------------------------------------------
'Author : a.p.r. pillai
'Date   : Feb-2010
'All Rights Reserved by www.msaccesstips.com
'------------------------------------------------------------------------

Dim WS As Workspace, msg As String
Dim UsrName As String, K As User, Flag As Boolean

Set WS = DBEngine.Workspaces(0)

'All the Users belong to the Common Group 'Users'
Flag = False
With WS.Groups("Users")
        For Each K In .Users
                  If K.Name = strUsrName Then
                          Flag = True
                          Exit For
                  End If
        Next
End With

If flag Then
     MsgBox "User Name: " & strUsrName & " Already Exists! "
End If

Check4UserAccount = flag

End Function

Type the following in the Debug Window (Immediate Window) and press Enter Key to run the above Code:

Check4UserAccount "SMITHJOHN"

If you have not run the first program to create the User Account SMITHJON, then to test the second Program, call the above function with the Admin User Name.

Type the following in the Debug Window (Immediate Window) and press Enter Key:

Check4UserAccount "Admin"

Earlier Post Link References:

Share:

Microsoft Date Time Picker Control

Introduction

In an earlier article, Animated Floating Calendar, we learned how to use the Calendar Control to simplify date entry form fields. In that method, a single calendar control was used for multiple date fields by automatically moving it near the selected field with a smooth unfolding animation.

This approach helps to save space on the Form; otherwise, we would need to place separate calendar controls for each date field.

Now, we have an even better alternative — the Microsoft Date and Time Picker (DTPicker), an ActiveX control that closely resembles a Combo Box and is extremely easy to use.

Learn its Simple Usage.

Let us try a simple example to learn how to use this Calendar for a Date Field on a Form.

  1. Import the following Objects from C:\Program Files\Microsoft Office\Office11\Samples\Northwind.mdb sample database:

    • Table: Employees
    • Form: Employees
  2. Open the Employees Form in Design View.

  3. Select the Company Info Tab.

  4. Select the ActiveX Control option from the Insert Menu.

  5. Select the Microsoft Date and Timer Picker Control from the displayed list and click OK to create a control on the Form.

  6. Move the control near the HireDate Field and resize it as shown in the sample design of the Form given below:

    Few Simple Rules of Date/Time Picker Control.

    • Before using the Date and Time Picker control with date fields, it’s important to understand a few simple rules.

      You can set the Control Source property of the Date and Time Picker to a field, such as HireDate, and remove the existing HireDate text box from the form.

      However, note that the HireDate field cannot be blank. If you navigate to a record where the HireDate field is empty, or if you try to add a new record without assigning a date, the control will display the following error message:

      “Can’t set the value to NULL when CheckBox property = FALSE.”

    This error message indicates that the HireDate field cannot be left blank, and you also cannot clear the date value from the field once it has been set—unless the CheckBox property of the Date and Time Picker control is set to Yes.

    Important Settings.

  7. First things first—make sure the Date and Time Picker control you added to the form is selected. Then, open the Property Sheet (by choosing View → Properties or pressing Alt + Enter) and make the following changes:

    • Set the Control Source property to HireDate.

    • Set the CheckBox property to Yes.

    When you navigate to a record, the Date and Time Picker will automatically display the date stored in the HireDate field. To change the existing hire date, simply move the calendar to the desired year and month, then click the required date.

    If you move to a record where the HireDate field is NULL, the check mark will disappear, and the field will appear disabled, indicating that it’s empty. However, the control may still display the date from the previously accessed record. If you open the calendar drop-down, that previous date will automatically populate the HireDate field. You can either remove the check mark to clear the field or select a new date from the calendar to overwrite the value.

    If you prefer to adjust the date manually—by incrementing or decrementing the day, month, or year like you would on a digital clock—set the UpDown property to Yes. This changes the calendar’s drop-down into a spin button control, replacing the standard calendar view.

    Once enabled, click any date segment (day, month, or year), and use the spin buttons to increase /decrease the value to your desired setting.

  8. You can experiment with the Date and Time Picker control, keeping the points mentioned above, to better understand how the calendar behaves under different settings.


    Settings for Time Value.

  9. If you want to enter time values instead of dates using the Date and Time Picker control, change its Format property value to 2. This automatically sets the UpDown property to Yes, replacing the drop-down calendar with a spin button control. You can then use the spin buttons to adjust each segment of the time value — hours (hh), minutes (mm), seconds (ss), and AM/PM — individually, just as explained earlier.


Share:

Form and Report Open Arguments

Introduction

When opening a Report or Form, you can pass several optional parameters as run-time arguments. These arguments help control the behavior of the report or form, such as filtering the output or changing the form’s open mode depending on the user’s profile.

If the current user belongs to a specific User Group, and that group has only read-only privileges, then the Form can be opened automatically in Read-Only Mode.

If the user does not belong to that group, the form can open in Normal Mode.

The following VBA function, CheckGroup(), checks whether the current user belongs to a specified User Group. Copy the code for this function into a Standard Module.

The CheckGroup() Function.

Public Function CheckGroup(ByVal strUsr As String, grpName As String) As String
'-----------------------------------------------------
'Author : a.p.r. pillai
'Date   : Feb-2010
'URL    : www.msaccesstips.com
'Remarks: All Rights Reserved by www.msaccesstips.com
'-----------------------------------------------------
Dim wsp As Workspace
Dim GrpArray() As Variant, grpcnt As Integer
Dim GrpOut As Variant, j As Integer

Set wsp = DBEngine.Workspaces(0)

grpcnt = wsp.Users(strUsr).Groups.Count - 1
ReDim GrpArray(0 To grpcnt) As Variant

'User may belong to more than one User Group
'Create an Array of Group Names
For j = 0 To grpcnt
    GrpArray(j) = wsp.Users(strUsr).Groups(j).Name
Next

'Compare Admins with the Array List
'if matches then 'Admins' will be output in grpout Array
GrpOut = Filter(GrpArray(), grpName, True)

CheckGroup = GrpOut(0)

End Function

The CheckGroup() function should be called from a Command Button’s Click event procedure (we will implement it shortly). This function checks the current user’s group and returns the User Group name, which can then be used to open the form in a specific mode.

Private Sub cmdOpenForm_Click()
Dim strGrp

strGrp = CheckGroup(CurrentUser, "Admins")

If strGrp = "Admins" Then
    DoCmd.OpenForm "Products", acNormal, , , acFormReadOnly
Else
    DoCmd.OpenForm "Products", acNormal
End If

End Sub

The CheckGroup() program creates a list of workgroups, checks whether the current user belongs to the Admins Group, and returns the result. If the result is Admins, the Products Form opens in Read-Only Mode; otherwise, it opens in Normal Mode.

Creating the Workgroups array is necessary because a single user can belong to multiple workgroups, such as Admins, Users (default), Supervisor, Manager, Editor, or any other group defined in the Workgroup Information File (.mdw).

The Filter() function searches the array for the text "Admins". If it is found, the value is stored in the GrpOut(0) element.

We cannot use the Filter() function inside a form module subroutine, because it conflicts with the form’s Filter property.

Regarding the Open arguments for forms and reports, you can pass the name of a query as a Filter argument or a WHERE condition (without including the word WHERE).

In addition, there is another parameter called OpenArgs, which allows you to pass a value to a form or report. You can then read this value in the class module of the form or report using the same OpenArgs variable, and use it for any purpose for which it was passed.

OpnArgs Example

We try out a simple example to learn the usage of a OpnArgs parameter. We need a few objects from the C:\Program Files\Microsoft Office\Office11\Samples\Northwind.mdb sample database.

  1. Import the following from the Northwind.mdb sample database:

    • Table: Products
    • Table: Categories
    • Query: Products by Category
    • Report: Products by Category
  2. Open a new Form and create a Combo Box with the Category Name from the Categories Table.

    A sample Form image is given below for reference.

  3. Select the Combo Box and display its Property Sheet (View -> Properties or press Alt+Enter).

  4. Change the Name Property value to cboCategory.

  5. Create a Command Button and change its Name Property value to cmdOpen and the Caption Property Value to Open Report.

  6. Select Event Procedure in the On Click Event Property and click on the build (...) Button to open the Class Module of the Form with the empty Sub-Routine lines.

  7. Copy and paste the following VBA Code overwriting the existing line, or copy and paste the middle line alone:

    Private Sub cmdOPen_Click()
       DoCmd.OpenReport "Products by Category", acViewPreview, , , , Nz(Me!cboCategory, "")
    End Sub
    
  8. Save the Form with the name Open Argument Demo or any other name you prefer.

    Modify the Report Module

  9. Open Products by Category Report in Design View.

  10. Display the Class Module (View - -> Code)

  11. Copy and Paste the following Code into the Class Module:

    Private Sub Report_Open(Cancel As Integer)
    Dim strFilter As String
    
    If IsNull([OpenArgs]) Then
       Exit Sub
    End If
    
    Report.Title.Caption = Report.Title.Caption & " (" & [OpenArgs] & ")"
    strFilter = "CategoryName = '" & [OpenArgs] & "'"
    Report.Filter = strFilter
    Report.FilterOn = True
    
    End Sub
    
  12. Save the Report with the Code.

  13. Open the Open Argument Demo Form in Normal View.

  14. Select a Product Category Name (say Beverages) in the Combo Box.

  15. Click on the Open Report Command Button.

    The Products by Category Report will open with only Beverage items on the Report, and the heading label is modified to show the Product category Name.

  16. Now, delete the Combo box's current value and click the Open Report Command Button.

This time, all products by category will appear on the report, and the heading will remain unchanged.

In the Report_Open event procedure, we check whether the OpenArgs variable contains a value. If it is Null, the subroutine terminates immediately.

Trial Run of First Two Programs.

Do the following to try the first two Programs given at the top of this page:

  1. Open the Open Argument Demo Form in Design View.

  2. Create a second Command Button on the Form.

  3. Display the Property Sheet of the Command Button (View -> Properties).

  4. Change the Name Property value to cmdOpenForm, and the Caption Property Value to Open Form.

  5. Display the Class Module (View -> Code).

  6. Copy and paste the second Program from the top into the Module and save the Open Argument Demo Form.

  7. Create a Tabular type Form for the Products Table and save the Form as Products.

  8. Open the Open Argument Demo Form and click on the Open Form Command Button.

  9. If you have not implemented Microsoft Access Security, you are by default the Admin User, a member of the Admins Group, and the Products Form will open in Read-Only mode.

Share:

PRESENTATION: ACCESS USER GROUPS (EUROPE)

Translate

PageRank

Post Feed


Search

Popular Posts

Blog Archive

Powered by Blogger.

Labels

Forms Functions How Tos MS-Access Security Reports msaccess forms Animations msaccess animation Utilities msaccess controls Access and Internet MS-Access Scurity MS-Access and Internet Class Module External Links Queries Array msaccess reports Accesstips WithEvents msaccess tips Downloads Objects Menus and Toolbars Collection Object MsaccessLinks Process Controls Art Work Property msaccess How Tos Combo Boxes Dictionary Object ListView Control Query VBA msaccessQuery Calculation Event Graph Charts ImageList Control List Boxes TreeView Control Command Buttons Controls Data Emails and Alerts Form Custom Functions Custom Wizards DOS Commands Data Type Key Object Reference ms-access functions msaccess functions msaccess graphs msaccess reporttricks Command Button Report msaccess menus msaccessprocess security advanced Access Security Add Auto-Number Field Type Form Instances ImageList Item Macros Menus Nodes RaiseEvent Recordset Top Values Variables Wrapper Classes msaccess email progressmeter Access2007 Copy Excel Export Expression Fields Join Methods Microsoft Numbering System Records Security Split SubForm Table Tables Time Difference Utility WScript Workgroup database function msaccess wizards tutorial Access Emails and Alerts Access Fields Access How Tos Access Mail Merge Access2003 Accounting Year Action Animation Attachment Binary Numbers Bookmarks Budgeting ChDir Color Palette Common Controls Conditional Formatting Data Filtering Database Records Defining Pages Desktop Shortcuts Diagram Disk Dynamic Lookup Error Handler External Filter Formatting Groups Hexadecimal Numbers Import Labels List Logo Macro Mail Merge Main Form Memo Message Box Monitoring Octal Numbers Operating System Paste Primary-Key Product Rank Reading Remove Rich Text Sequence SetFocus Summary Tab-Page Union Query User Users Water-Mark Word automatically commands hyperlinks iSeries Date iif ms-access msaccess msaccess alerts pdf files reference restore switch text toolbar updating upload vba code