Microsoft Access VBA Tutorials for self-paced learning, Class Modules, SQL Techniques, and AI Integration Guides.

Showing posts with label Split. Show all posts
Showing posts with label Split. Show all posts

Join Split Array Functions-2

Join Split Array Functions-2.

This is the continuation of last week's Article: Join Split Array Functions

  1. If you haven’t reviewed the fundamentals of the functions mentioned above, I recommend doing so by following the link provided earlier before continuing.

    Since the Join() and Split() functions are closely related, this is a good time to explore a real-world example that demonstrates their use. While the approach we are about to take may not be the simplest solution to the problem at hand, it will clearly illustrate how these functions work and help deepen your understanding of their practical applications.

  2. Import Employees Table from the Northwind sample database: C:\Program Files\Microsoft Office\Office11\samples\Northwind.mdb 

  3. Open a new Query in SQL View (don't select any Table from the displayed list).

  4. Copy and paste the following SQL String into the SQL editing window and save the Query with the name EmployeeSelectQ

    .
    SELECT Employees.*
    FROM Employees;
    
  5. Design a new Form similar to the sample image shown below. You can use the Form Wizard to create it quickly, and set EmployeeSelectQ as the record source for the Form. 

  6. Add a Text Box and a CommandButton at the bottom of the design.

  7. Select the Text Box and display the Property Sheet (View -> Properties or Design -> Property Sheet in 2007).

  8. Change the Name Property Value to txtCodes.

  9. Select the CommandButton, change the Name Property value to cmdFilter, and the Caption Property value to Apply Filter.

  10. Select the Child label of the Text Box and change its Caption to Employee Codes:.

  11. Display the Form's VBA Code Module (View -> Code or click the View Code toolbar button from the 2007 Design Menu).

  12. Copy and paste the following VBA Code into the Form Module and save the Form with the name EmployeeSelect:

    Private Sub cmdFilter_Click()
    Dim txt_Codes As String, varList As Variant
    Dim varCodes As Variant, j As Integer, x
    Dim maxCodes As Variant, invalid_Codes As String
    
    txt_Codes = Nz(Me.txtCodes, "")
    maxCodes = DMax("EmployeeID", "Employees")
    
    If Len(txt_Codes) = 0 Then
      varList = Null
    Else
       'Split the items into the array.
      
      '(Here Array() Function will not work
      'becuase the values in txtCodes variable is a String
      'and will be treated as a single item).
    
      varCodes = Split(txt_Codes, ",")
      
      'Validation check
      invalid_Codes = ""
      For j = 0 To UBound(varCodes)
         x = Val(varCodes(j))
         If x < 1 Or x > maxCodes Then
            invalid_Codes = invalid_Codes & Format(x, "0 ")
         End If
      Next
      If Len(invalid_Codes) > 0 Then
         MsgBox "Invalid Employee Codes: " & invalid_Codes & vbCr & vbCr & "Correct and retry."
         Exit Sub
      End If
      'here "varList = txt_Codes" is also works
      'because txt_Codes values are separated with commas already
      varList = Join(varCodes, ",")
    End If
    
      'Call the EmployeeFilter() function
      EmployeeFilter varList
      Me.RecordSource = "EmployeeSelectQ"
      Me.Requery
    
    End Sub
  13. Press Alt+F11 to open the VBA Editing window. If you have already closed it, select Module from the Insert Menu to add a new Standard Module.

  14. Copy and paste the following EmployeeFilter() Function VBA Code into the Standard Module and save it:

    Public Function EmployeeFilter(ByVal Criteria As Variant)
    Dim strsql0 As String, sql As String
    Dim db As Database, qryDef As QueryDef
    
    strsql0 = "SELECT Employees.* FROM Employees WHERE (((Employees.EmployeeID) In ("
    
    Set db = CurrentDb
    Set qryDef = db.QueryDefs("EmployeeSelectQ")
    
    If IsNull(Criteria) Or Len(Criteria) = 0 Then
        sql = "SELECT Employees.* FROM Employees;"
    Else
        Criteria = Criteria & ")));"
        sql = strsql0 & Criteria
    
    End If
        qryDef.SQL = sql
        db.QueryDefs.Refresh
    
    End Function
  15. Open the EmployeeSelect Form in a normal view. The sample image of the Form is given below:

  16. Enter Employee IDs 2, 3, 7, and click the Apply Filter Command Button.

    Now, the Employee Select Form has only three records, with employee codes 2, 3 & 7.

  17. Delete all the Text Box contents and click the Apply Filter Command Button.

The filter action is reversed, and the Employee Table records are now available on the Form.  In other words, it works like a Reset command when the TextBox is empty.

You may try it out with a different Employee ID.

The values entered into the TextBox must be within the range of the available Employee Code. The numbers entered outside this range will display an Error message and abort the program.

Share:

Join Split Array Functions

Join Split Array Functions.

The Join() and Split() functions in MS Access are not widely used, but they can be both interesting and surprisingly powerful. To understand their potential, let’s examine them. Later, we will write a program to demonstrate how these functions can be applied in real-world scenarios.

We will start with the Array() function. But before exploring it in detail, let’s first review how to define an array variable and assign a value to each array element.

Demo of Array() Function

'Dimension the array for six elements
Dim varNumber(0 To 5) As Variant, j As Integer
For j = 0 To 5
    varNumber(j) = j + 1
Next
  1. The first statement in the program defines a variable named varNumber as a Variant Type Array for 6 elements.

  2. Another variable j is defined as an integer type that will be used as an index variable in the For. . .Next loop.

  3. The next three statements in the above program assign values 1 to 6 to the Array elements as:

  • varNumber(0) = 1
  • varNumber(1) = 2
  • varNumber(2) = 3
  • varNumber(3) = 4
  • varNumber(4) = 5
  • varNumber(5) = 6

We can do this task with only one statement if we use the Array() Function as below:

varNumber = Array(1, 2, 3, 4, 5, 6)

Unlike the first example, we don’t need to define the variable with a fixed number of elements—the array is automatically sized based on the number of items in the argument list. In this case, we assigned constant values from 1 to 6 to the array elements indexed 0 to 5.

Another important point to note is that the target variable (varNumber) must always be declared as a Variant type. This provides greater flexibility, allowing you to assign mixed data types to different elements of the array, as shown in the example below:

    varNumber = Array("Nancy", 25, "Andrew", 30, 172.5)

We have assigned a mix of String, Integer, and Double Data Types to different elements of the same array.  Again, we have used constant values to assign to the array.

The Array Function can accept several parameters as a single block, without defining several parameter declarations in the main program.

You can use Constants, Variables, or data Field Values to assign values to the array.

Example-1:

a = "Nancy"
 b = 25
 c = 172.5
 varNumber = Arrary(a,b,c)

Example-2:

varNumber = Array(Me![FirstName],Me![BirthDate],Me![Address])

Next, we will explore the Join() function. To better understand how it works, let’s create another array of values and use it as input for this function.

varNumber = Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat")

We have the names of weekdays in the array variable varNumber.

varNumber(0) = "Sun"
 .
 . 
 . 
 varNumber(6) = "Sat" 

If you want to combine all seven elements of this array variable into a single string, with each item separated by commas (for example: Sun, Mon, Tue, Wed, Thu, Fri, Sat), you can do so with the following statements:

 Dim strWeeks as string, j as integer
 strWeeks=""
For j = 0 to 6
   if j=6 then
     strWeeks = strWeeks & varNumber(j)
   Else
     strWeeks = strWeeks & varNumber(j) & ","
   end if
Next

Join() Function:

The above task takes only one statement with the Join() Function:

strWeeks = Join(varNumber,",")

The first parameter of the Join() function is the array containing the values to be combined into a single string. The second parameter specifies the separator character inserted between the array elements. If this parameter is omitted, a space is used as the default separator. Otherwise, the character or string you specify will be used as the separator.   

Result: strWeeks = "Sun,Mon,Tue,Wed,Thu,Fri,Sat"

Split() Function:

Split() is the complementary Function of Join().  It splits the individual items, separated by the delimiter character, and stores the values into an array variable of Variant Type.

We need the following lines of code to do the same task as the Split() Function:

Dim strWeeks(0 To 6) As Variant, strtxt As String
Dim j As Integer, k As Integer

strtxt = "Sun,Mon,Tue,Wed,Thu,Fri,Sat"
k = 0
For j = 1 To Len(strtxt) Step 4
   strWeeks(k) = Mid(strtxt, j, 3)
   k = k + 1
Next

With the use of the Split() Function, it takes only one statement to do the job that we did with the above program:

 strWeeks = Split(strTxt,",")

Next week, we will use these functions in a Program to redefine a Query linked to a Form to filter and view data.

Earlier Post Link References:

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 External Links Queries Array Class Module msaccess reports Accesstips msaccess tips WithEvents Downloads Objects Menus and Toolbars MsaccessLinks Process Controls Art Work Collection Object Property msaccess How Tos Combo Boxes ListView Control Query VBA msaccessQuery Calculation Dictionary Object 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 Recordset Top Values Variables msaccess email progressmeter Access2007 Copy Excel Expression Fields Join Methods Microsoft Numbering System RaiseEvent Records Security Split SubForm Table Tables Time Difference Utility WScript Workgroup Wrapper Classes 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 Export 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