Removing special characters VBA Excel

pixie picture pixie · Jun 23, 2014 · Viewed 156.9k times · Source

I'm using VBA to read some TITLES and then copy that information to a powerpoint presentation.

My Problem is, that the TITLES have special characters, but Image files that I am also coping over do not.

The TITLE forms part of a path to load a JPEG into a picture container. E.g. "P k.jpg", but the title is called "p.k".

I want to be able to ignore the special characters in the TITLE and just get it to see a space instead so it picks up the right JPG file.

Is that possible?

Thank you!

Answer

David Zemens picture David Zemens · Jun 23, 2014

What do you consider "special" characters, just simple punctuation? You should be able to use the Replace function: Replace("p.k","."," ").

Sub Test()
Dim myString as String
Dim newString as String

myString = "p.k"

newString = replace(myString, ".", " ")

MsgBox newString

End Sub

If you have several characters, you can do this in a custom function or a simple chained series of Replace functions, etc.

  Sub Test()
Dim myString as String
Dim newString as String

myString = "!p.k"

newString = Replace(Replace(myString, ".", " "), "!", " ")

'## OR, if it is easier for you to interpret, you can do two sequential statements:
'newString = replace(myString, ".", " ")
'newString = replace(newString, "!", " ")

MsgBox newString

End Sub

If you have a lot of potential special characters (non-English accented ascii for example?) you can do a custom function or iteration over an array.

Const SpecialCharacters As String = "!,@,#,$,%,^,&,*,(,),{,[,],},?"  'modify as needed
Sub test()
Dim myString as String
Dim newString as String
Dim char as Variant
myString = "!p#*@)k{kdfhouef3829J"
newString = myString
For each char in Split(SpecialCharacters, ",")
    newString = Replace(newString, char, " ")
Next
End Sub