これを試して
「 @#$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