试试这个
使用类似“ @#$1_qwerty@#@!# _1234 ”的字符串对其进行了测试。该CleanText
函数会将其更改为“ qwerty_1234 ”
书签Name
将接受a-z/A-Z
作为第一个字符和a-z/A-Z/0-1/_
其余字符。
Option Explicit
Sub AddBookMark()
Dim sText As String
sText = CleanText(Application.Selection.Text)
If sText = "" Then
MsgBox "Invalid Name"
Exit Sub
End If
With ActiveDocument.Bookmarks
.Add Range:=Selection.Range, Name:=sText
.DefaultSorting = wdSortByName
.ShowHidden = False
End With
End Sub
Function CleanText(strInput As String) As String
Dim i As Long, strTemp As String
strInput = Trim(strInput)
Do Until (Asc(Left(strInput, 1)) > 65 And Asc(Left(strInput, 1)) < 90) Or _
(Asc(Left(strInput, 1)) > 97 And Asc(Left(strInput, 1)) < 122) Or Len(strInput) = 0
Select Case Asc(Left(strInput, 1))
Case 65 To 90, 97 To 122
Case Else: strInput = Mid(strInput, 2)
End Select
Loop
strTemp = Left(strInput, 1)
For i = 2 To Len(strInput)
Select Case Asc(Mid(strInput, i, 1))
Case 65 To 90, 97 To 122, 95, 48 To 57
strTemp = strTemp & Mid(strInput, i, 1)
End Select
Next
ExitF:
CleanText = strTemp
End Function