通过所选文本创建书签



我正在尝试创建一个宏,该宏将在所选文本的位置和名称处创建一个位置书签。

我有下面的代码,它说书签名称不好。

 Sub AddBookMark()
 Dim sText As String
 sText = Application.Selection.Text
 sText = Replace(sText, vbCrLf, "")
 sText = Replace(sText, Chr(10), " ")
 sText = Replace(sText, Chr(182), " ")
With ActiveDocument.Bookmarks
    .Add Range:=Selection.Range, Name:=sText
    .DefaultSorting = wdSortByName
    .ShowHidden = False
End With
End Sub

有没有办法根据所选文本将书签名称设置为变量?

试试这个

使用类似"@#$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

最新更新