Remove Non-Printable Characters From A String
The code below will remove all non-printables from a string except the carriage return and line feed characters. The program also demonstrates using "typecast" notation for constants, passing values to a function "By Value" instead of "By Reference", and a very fast way to build a new string without continuously concatenating.
Program Code
Option Explicit
Sub TestRemovalOfNonPrintable()
Dim strContainsTabCharacters As String
Dim strPrintable As String
strContainsTabCharacters = "A" & vbTab & "B" & vbTab & "C" & vbTab & "D"
strPrintable = RemoveNonPrintable(strContainsTabCharacters)
MsgBox ("Length Of Original String = " & Len(strContainsTabCharacters))
MsgBox ("Length Of Neww String = " & Len(strPrintable))
End Sub
Function RemoveNonPrintable(ByVal strIn As String) As String
Dim i As Long ' To Read Each Character Of The Input String
Dim j As Long ' Characters That Are Accepted
Dim strChar As String
' ********************************************************************
' This Also Demonstrates Two Key Concepts:
' (1) Pass a parameter By Value (original value does not get modified)
' (2) Typecast characters used in constants
' Typecast Characters: &=Long, %=Integer, !=Single, #=Double
' @=Currency, $=String
' ********************************************************************
j = 0
For i = 1& To Len(strIn)
strChar = Mid$(strIn, i, 1&)
Select Case Asc(strChar)
Case 10, 13, Is >= 32
j = j + 1&
Mid$(strIn, j, 1&) = strChar
End Select
Next
RemoveNonPrintable = Left$(strIn, j) ' Shorter String Now
End Function