I want to search a string for a character. I'm using InStr
and
I want to return that character which will be passed to a user form.
My code works fine if I manually assign a string to a variable. For example:
ProtFunc = "21G_TRIP"""
The code will find the "
and then return with a message box saying:
Bad Character "
The problem comes when using a selection from the Word document. It finds the "
but doesn't return the character.
See code below:
Note: Parts of the code I have seen used from various forums.
Sub CharFind ()
'For testing purposes
'ProtFunc = "21G_Trip"""
ProtFunc = Selection
'Checking the ProtFunc for invalid Characters
'This searches for invalid characters in the ProtFunc String and will inform user of error
'Forsome reason the search picks up an additional character,
'the line below removes the last charater of the ProtFunc
'ProtFunc = Left(ProtFunc, Len(ProtFunc) - 1)
'The following characters will produce invalid file paths: \ / : * ? " < > |
'Additionally the following are checked too: , . ;
strTemp = ProtFunc
If (InStr(1, strTemp, "/") > 0) Or (InStr(1, strTemp, "") > 0) Or _
(InStr(1, strTemp, "*") > 0) Or (InStr(1, strTemp, "?") > 0) Or _
(InStr(1, strTemp, "|") > 0) Or (InStr(1, strTemp, """") > 0) Or _
(InStr(1, strTemp, "<") > 0) Or (InStr(1, strTemp, ">") > 0) Or _
(InStr(1, strTemp, ":") > 0) Then
'Assigning the invaild charater to be displayed
If (InStr(1, strTemp, ",") > 0) Then Char = "," Else
If (InStr(1, strTemp, ".") > 0) Then Char = "." Else
If (InStr(1, strTemp, ":") > 0) Then Char = ":" Else
If (InStr(1, strTemp, ";") > 0) Then Char = ";" Else
If (InStr(1, strTemp, "\") > 0) Then Char = "\" Else
If (InStr(1, strTemp, "/") > 0) Then Char = "/" Else
If (InStr(1, strTemp, "*") > 0) Then Char = "*" Else
If (InStr(1, strTemp, "?") > 0) Then Char = "?" Else
If (InStr(1, strTemp, """") > 0) Then Char = """" & BDBDBDB Else
If (InStr(1, strTemp, "<") > 0) Then Char = "<" Else
If (InStr(1, strTemp, ">") > 0) Then Char = ">" Else
If (InStr(1, strTemp, "|") > 0) Then Char = "|"
MsgBox "Bad Character." & vbCr & Char
'Assigning the the invaild character to the ListBox in the User Form ErrorMsgProtName
ErrorMsgProtName.ListBox1.AddItem (Char)
'Showing the User Form ErrorMsgProtName
ErrorMsgProtName.Show
'Clearing the ListBox in the User Form ErrorMsgProtName for the next round
ErrorMsgProtName.ListBox1.Clear
Else
MsgBox ProtFunc & "Is fine"
End If
'InvalChar Search - End
End Sub
Word is probably using a "smart quote" instead of a standard quote:
” Smart quote. Unicode hex value &H201D.
" Standard quote. Unicode hex value &H22.
The smart quote is fine for use in a Windows path, so there's no need to remove it, unless you really want to.
BTW, a regex would make your life much easier:
Dim re
Set re = CreateObject("VBScript.RegExp")
re.Pattern = "[\\/:\*\?""<>\|]"
If re.Test(strTemp) Then
MsgBox "Bad Character." & vbCr & re.Execute(strTemp)(0)
Else
MsgBox strTemp & " is fine"
End If