This article shows you how to create a custom function to strip invalid
characters or characters that you do not want from a string. You can use
this function in queries and in text input boxes.
Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements.
↑ Back to the top
To strip invalid characters or characters that you do not want from a
string, follow these steps:
- Create a module and type the following line in the Declarations
section if it is not already there:
- Type the following procedure:
' --------------------------------------------------
' Function StripString()
'
' Returns a string minus a set of specified chars.
' --------------------------------------------------
Function StripString(MyStr As Variant) As Variant
On Error GoTo StripStringError
Dim strChar As String, strHoldString As String
Dim i As Integer
' Exit if the passed value is null.
If IsNull(MyStr) Then Exit Function
' Exit if the passed value is not a string.
If VarType(MyStr) <> 8 Then Exit Function
' Check each value for invalid characters.
For i = 1 To Len(MyStr)
strChar = Mid$(MyStr, i, 1)
Select Case strChar
Case ".", "#", ",", "-"
' Do nothing
Case Else
strHoldString = strHoldString & strChar
End Select
Next i
' Pass back corrected string.
StripString = strHoldString
StripStringEnd:
Exit Function
StripStringError:
MsgBox Error$
Resume StripStringEnd
End Function
- To test this function, type the following line in the Immediate window, and then press ENTER:
? StripString("Test.#,-")
Note that the function prints the word "Test" in the Immediate window. The invalid characters (".#,-") are successfully stripped from the test string.
↑ Back to the top
For more information about information about string manipulation, click Microsoft Access Help on the
Help menu, type Len in the Office Assistant or
the Answer Wizard, and then click Search to view the topics
returned.
↑ Back to the top