String and Data Manipulation Programming Examples
 

Home | EXCEL VB Programming (XL97-2003) | ACCESS Programming | EXCEL VB.Net Programming | EXCEL Spreadsheet FunctionsMaterial  Management | Master Scheduling & Production Planning | Forecasting Methods & Techniques | About me | Guestbook  


Access Programming
Access Database basic
Objects, Collections, Properties and Methods
DoCmd Objects
Forms, Control and Events
ADO (ActiveX Data Objects)
ADO Examples
ADOX (ADO Extensions)
ADOX Examples
Jet SQL (Structured Query Language)
Jet SQL Examples
String manipulation
Integrating Access/Excel
Access 2003 VBA Constants
 
   

Microsoft Access: String and Data Manipulation Programming Examples

Functions

Description

Multiple_InStr() To retrieve all records that contain your specified string from a table. 
TrimSpaces() To trim records in a field, and print the trimmed the records in another field.
Remove_First_Space(Arg1) To remove the first space that is found in a string.
ReverseFind_Replace() To find and replace a text within a string in a table field.
GetLastPortionOfString(Arg1) To return the last text, word, one or a continuation of numbers, in the strings of the table field.
ImpossibleCounting() To count in one or more field, on how many numbers, upper and lower case, and other characters.
Sample expressions To to extract the different portions of a text string.

 

Option Compare Database

' Purpose: To retrieve a desired string from a field in a table

Sub Multiple_InStr()
Dim conn As ADODB.Connection
Dim rs As New ADODB.Recordset
Dim ssql As String
Dim found_city As Integer
Set conn = CurrentProject.Connection

ssql = "Select * From Table1"
rs.Open ssql, conn, adOpenKeyset, adLockOptimistic

Do Until rs.EOF
found_city = 0
found_
city = InStr(1, rs.Fields("Countries"), "Singa")
  If found_city > 0 Then
     Do Until found_city = 0
        Debug.Print rs.Fields("
Countries") & " " & found_city
        found_
city = InStr(found_city + 1, rs.Fields("Countries"), "Singa")
     Loop
  End If
rs.MoveNext
Loop

rs.Close
Set rs = Nothing
Set conn = Nothing
End Sub

Go To Top


' Purpose: To trim a field in Table1. In this example, it places the trimmed string into 2nd field, and also count the number of spaces that are removed and print the counts into a 3rd field.

Sub TrimSpaces()
Dim conn As ADODB.Connection
Dim rs As New ADODB.Recordset
Dim ssql As String
Dim originalLength As Integer

Set conn = CurrentProject.Connection
ssql = "Select * From Table1"

rs.Open ssql, conn, adOpenKeyset, adLockOptimistic
Do Until rs.EOF
   originalLength = Len(rs.Fields("Field_BeforeTrim"))
   rs.Fields("Field_AfterTrim") = Trim(rs.Fields("Field_BeforeTrim"))
   rs.Fields("Counter_SpacesRemoved") = originalLength - Len(rs.Fields("Field_AfterTrim"))
   rs.MoveNext
Loop

rs.Close
Set rs = Nothing
Set conn = Nothing
End Sub

Go To Top


' Purpose: To remove the first space that is found in a string.

Function Remove_First_Space(full_string As String) As String
Dim str_length As Integer
Dim pos As Integer
str_length = Len(full_string)

For pos = 1 To str_length
  If Mid(full_string, pos, 1) = " " Then
   
' Change to -2, for example, if like to have one space + one more character removed, moving leftward.
    remove_first_space=Left(full_string, pos-1)& Right(full_string, Len(full_string)-pos)
    Exit For
  End If
Next pos
End Function


' Display as "WilliamTan"
Sub example()
MsgBox remove_first_Space("William Tan")
End Sub

' Or use the function in Design Query and Make-Table Query, by using an SQL string in example below.
SELECT Table1.*, remove_first_space([Material_Memo]) AS Expr1 INTO Table2
FROM Table1;

Go To Top


' Purpose: To find a text in a string, from reverse right-to-left, and replace a found text with another text in a field name "Field_Rojak". (The Replace function includes 1 sub-string search & up to 10 substitutions).

Sub ReverseFind_Replace()
Dim conn As ADODB.Connection
Dim rs As New ADODB.Recordset
Dim ssql As String
Dim original_string, search_string As String
Dim replace_string, new_string As String

search_string = "-"   
' change as it suits
replace_string = "/"

Set conn = CurrentProject.Connection
ssql = "Select * From Table1"
rs.Open ssql, conn, adOpenKeyset, adLockOptimistic

Do Until rs.EOF
original_string = rs.Fields("Field_Rojak").Value

new_string = Replace(StrReverse(original_string), StrReverse(search_string), _
StrReverse(replace_string), 2, 10)
new_string = StrReverse(new_string)

rs.Fields("Field_Rojak") = new_string
rs.MoveNext
Loop

rs.Close
Set rs = Nothing
Set conn = Nothing
End Sub

Go To Top


' Purpose: Use InStr function to locate the last occurrence of the search string, then replace it with the desired value.

Sub Find_Replace_LastOccurence()
Dim original_string
Dim search_string As String
Dim replace_string
Dim new_string As String
Dim found_position As Integer
Dim last_found_position As Integer

original_string = "strangely_they_think_singapore_is_a_city_of_singapore"
search_string = "singapore"
replace_string = "malaysia"

found_position = InStr(1, original_string, search_string)
' If one occurence exists then keep checking and store each successive found position in last_found_position
If found_position > 0 Then
   last_found_position = found_position
   Do Until found_position = 0
      found_position = InStr(found_position + 1, original_string, search_string)
      If found_position > 0 Then
last_found_position = found_position
   Loop
      ' Now use Replace with knowing where last occurence starts
   new_string = Left(original_string, last_found_position - 1) & _
   Replace(original_string, search_string, replace_string, last_found_position)
End If
MsgBox new_string
End Sub

Go To Top


' Purpose: To return the last text, word, one or a continuation of numbers, in the strings of the table field.

Function GetLastPortionOfString(sStr As String) As String
Dim i As Integer, j As Integer
Dim s As String, tmp As String
Dim last_text As String, Hold As String
Dim charFound As Integer

tmp = ""
last_text = ""
charFound = False
Hold = sStr
j = Len(sStr)

For i = j To 1 Step -1
   s = Right(Hold, 1)
   If s = " " Then
      If Not charFound Then
      '* skip spaces at end of string.
      Else
         last_text = tmp
      Exit For
      End If
   Else
      charFound = True
      tmp = s & tmp
   End If

   If Len(Hold) > 0 Then
      Hold = Left(Hold, Len(Hold) - 1)
   End If
Next i

If last_text = "" And tmp <> "" Then
   last_text = tmp
End If

GetLastPortionOfString = Trim(last_text)
'MsgBox "lastword =" & Trim(last_text)
End Function

Go To Top


' Purpose: To count in a table's field on how many upper case and lower case characters, numbers, and other characters.

Sub ImpossibleCounting()
Dim data As String
Dim data_length As Integer, char_loop As Integer, number_count As Integer
Dim upper_case_count As Integer, lower_case_count As Integer, other_count As Integer

Dim conn As ADODB.Connection
Dim rst As New ADODB.Recordset
Dim sql As String
Dim originalLength As Integer

Set conn = CurrentProject.Connection
sql = "Select * From Table1"
rst.Open sql, conn, adOpenKeyset, adLockOptimistic

number_count = 0
upper_case_count = 0
lower_case_count = 0
other_count = 0

Do Until rst.EOF
   data = rst.Fields("Field1")
   data_length = Len(data)

   For char_loop = 1 To data_length
     
' Asc function returns an integer representing the character code corresponding to the first letter in a string.
      Select Case Asc(Mid(data, char_loop, 1))

         Case 48 To 57
            number_count = number_count + 1
         Case 65 To 90
            upper_case_count = upper_case_count + 1
         Case 97 To 122
            lower_case_count = lower_case_count + 1
         Case Else
            other_count = other_count + 1
         End Select
   Next char_loop

   rst.MoveNext
Loop

Debug.Print number_count & " numbers found"
Debug.Print upper_case_count & " upper case letters found"
Debug.Print lower_case_count & " lower case letters found"
Debug.Print other_count & " other characters found"

rst.Close
Set rst = Nothing
Set conn = Nothing
End Sub

Go To Top


' Purpose: basic sample expressions that you can use to extract a portion of a text string.

"William Gates" - Returned by Expression: William as First Name
Expr: Left([Names],InStr(1,[Names]," ")-1)

"Gates, William " - Returned by Expression: William as First Name
Expr: Right(Trim([Names]),Len(Trim([Names]))-InStr(1, [Names]," "))

"
William H. Gates" - Returned by Expression: William as First Name
Expr: Left([Names],InStr(1,[Names]," ")-1)

"William Gates" - Returned by Expression: Gates as Last Name
Expr: Right(Trim([Names]),Len(Trim([Names]))-InStr(1, [Names]," "))

"
Gates, William " - Returned by Expression: Gates as Last Name
Expr: Left([Names],InStr(1,[Names],",")-1)

"William H. Gates" - Returned by Expression: Gates as Last Name
Expr: Right(Trim([Names]),Len(Trim([Names]))-InStr(InStr (1, [Names]," ")+1,[Names]," "))

"William Gates" or "William H. Gates" - Returned by Expression: Gates as Last Name
Expr: IIf(InStr(InStr([names]," ")+1,[names]," ") <>0, Right([names],Len([names])-InStr(InStr([names]," ")+1, _
[names]," ")),Right([names],Len([names])-InStr([names]," ")))

"
William H. Gates" - Returned by Expression: H.  as Middle Initial
Expr: Trim(Mid([Names],InStr(1,[Names]," ")+1,InStr(InStr (1, [Names], " ")+1,[Names]," ")-InStr(1,[Names]," ")))

"Gates, William  P." - Returned by Expression: H. as Middle Initial
Expr: Right(Trim([Names]),Len(Trim([Names]))-InStr (InStr(1, [Names]," ")+1,[Names]," "))

"William Gates" or "William H. Gates" - Returned by Expression: P. or blank as Middle Initial
Expr: Trim(Mid([names], InStr(1, [names], " ") + 1, IIf(InStr(InStr(1, [names], " ") + 1, [names], " ") = 0, 0, _
InStr(InStr(1, [names], " ") + 1, [names], " ") - InStr(1, [names], " "))))

ZipCode, "98052-6399" - Returned by Expression: 98052 as ZipCode
Expr: Left([ZipCode],5)

Area Code & Phone (425) 635-7050 - Returned by Expression: 425 as Area Code
Expr: Mid([Phone], 2, 3)

Area Code & Phone (425) 635-7050 - Returned by Expression: 635-7050 as Phone
Expr: Right(Trim([Phone]),8)

Go To Top

       




This site was created in February 2007
by William Tan