我想在字符串中搜索字符。我正在使用InStr
和
我想返回将传递给用户表单的那个字符。
如果我手动将字符串分配给变量,我的代码可以正常工作。例如:
ProtFunc = "21G_TRIP"""
代码将找到"
,然后返回一个消息框说:
坏人物"
使用Word文档中的选项时出现问题。它找到了"
,但没有返回角色。
见下面的代码:
注意:我见过的部分代码来自各种论坛。
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
答案 0 :(得分:1)
Word可能使用“智能引用”而不是标准引用:
” Smart quote. Unicode hex value &H201D.
" Standard quote. Unicode hex value &H22.
智能引用可以在Windows路径中使用,因此除非您真的想要,否则无需删除它。
顺便说一句,正则表达式会让你的生活变得更轻松。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