MS Access: Remove Special characters or Extract only alphanumeric values

I needed to extract only alphabet and numeric values from a given string. This script can perform my task.

Function fn_ReplaceSChar(ByVal strWord As String) As String
' this is VBA string for replacing special characters
' ASCII code (0 - 31)
Dim strChar, strResult As String
Dim intPos, intLen As Integer
On Error GoTo Err_SuperTrap
intPos = 0
intLen = Len(strWord)
strResult = ""
If intLen = 0 Then
fn_ReplaceSChar = strWord
' if string length = 0, return result now
Else
For intPos = 1 To intLen
strChar = Mid(strWord, intPos, 1)
' replace special char by blank space

If Asc(strChar) < 32 Then
strChar = Chr(32)
End If

strResult = strResult + strChar
Next intPos
End If

' replace 2 blanks by one
strResult = Replace(strResult, Chr(32) & Chr(32) & Chr(32), Chr(32))
strResult = Trim(Replace(strResult, Chr(32) & Chr(32), Chr(32)))

fn_ReplaceSChar = strResult

Exit_SuperTrap:
Exit Function

Err_SuperTrap:

MsgBox Err.Description
Resume Exit_SuperTrap
End Function

Initially, I tried creating a function to obtain results dynamically, but I could not achieve it. But I wrote a function to update cleaned string to the available column Normalizedstring from the given string available in column InputString, which can be run through a form.
Keep your junk data in an access table(Table1) with column name InputString. Have a column created Normalizedstring in the same table.
Public Sub Removespecialchars()
Dim n As Integer
Dim tbl As TableDef, fld As Field
Set db = CurrentDb
Dim str(7) As String

Dim i As Integer
db.Execute "UPDATE Table1 SET NormalizedString = NULL"
db.Execute "UPDATE Table1 SET NormalizedString = len([InputString])"
db.Execute "UPDATE Table1 SET NormalizedString = '0' WHERE (((NormalizedString) Is Null))"
n = DMax("CInt([NormalizedString])", "Table1")
db.Execute "UPDATE Table1 SET NormalizedString = ''"
db.Execute "UPDATE Table1 SET InputString = trim([InputString])"
For i = 1 To n
db.Execute "UPDATE Table1 SET NormalizedString = [NormalizedString]+Mid([InputString]," & i & ",1) WHERE (((Mid([InputString]," & i & ",1)) Between 'A' And 'Z' Or (Mid([InputString]," & i & ",1)) Between '0' And '9'))"
Next i
End Sub

1 comment:

  1. Thank you for sharing such valuable information. This blog has given me a fresh perspective on the topic. As a content creator, the auto clicker has become my secret weapon. It ensures seamless mouse clicks while I focus on crafting engaging content for my audience. Must be visit.

    ReplyDelete