【问题】
在word中,想要通过vba宏,去给选中的文字添加页内链接。
已经实现了如下代码,选中需要的文字:
MsgBox “———-1.add CR”
ActiveDocument.Select
ActiveDocument.GoTo what:=wdLine, which:=wdGoToFirst
Do
With Selection.Find
.MatchWildcards = True
.Forward = True
.ClearFormatting
.MatchWholeWord = True
.MatchCase = False
‘.Wrap = wdFindContinue
.Execute FindText:=”【*】”
End With
Loop While (Selection.Font.Superscript = True)
‘MsgBox “now is normal text”
Selection.InsertAfter vbCrLf
Do
With Selection.Find
.MatchWildcards = True
.Forward = True
.ClearFormatting
.MatchWholeWord = True
.MatchCase = False
‘.Wrap = wdFindContinue
.Execute FindText:=”【*】”
End With
Selection.InsertAfter vbCrLf
Selection.Start = Selection.End
Loop While (Selection.Find.Found = True)
MsgBox “———-2. set to heading”
ActiveDocument.Select
ActiveDocument.GoTo what:=wdLine, which:=wdGoToFirst
Do
With Selection.Find
.MatchWildcards = True
.Forward = True
.ClearFormatting
.MatchWholeWord = True
.MatchCase = False
‘.Wrap = wdFindContinue
.Execute FindText:=”【*】”
End With
Loop While (Selection.Font.Superscript = True)
‘MsgBox “now is normal text”
Selection.Range.Style = wdStyleHeading2
Do
With Selection.Find
.MatchWildcards = True
.Forward = True
.ClearFormatting
.MatchWholeWord = True
.MatchCase = False
‘.Wrap = wdFindContinue
.Execute FindText:=”【*】”
End With
Selection.Range.Style = wdStyleHeading2
Loop While (Selection.Find.Found = True)
然后参考了录制宏去添加页内链接生成的代码:
Sub Macro1()
‘
‘ Macro1 Macro
‘ 宏在 2011-1-8 由 USER 录制
‘
ChangeFileOpenDirectory “E:downloadautoProcessWordFile”
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:=””, _
SubAddress:=”_【2】”, ScreenTip:=””, TextToDisplay:=”【2】”
End Sub
其中【2】,是前面代码已经实现添加了对应的标题的文字,SubAddress:=”_【2】”, 即页内跳转到标题为”【2】”的位置。
照葫芦画瓢,添加了如下代码:
MsgBox “———-3. link to heading”
ActiveDocument.Select
ActiveDocument.GoTo what:=wdLine, which:=wdGoToFirst
Do
With Selection.Find
.MatchWildcards = True
.Forward = True
.ClearFormatting
.MatchWholeWord = True
.MatchCase = False
‘.Wrap = wdFindContinue
.Execute FindText:=”【*】”
End With
‘ChangeFileOpenDirectory ActiveDocument.Path & “”
‘ChangeFileOpenDirectory ActiveDocument.Path
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:=””, SubAddress:=”_” & Selection.Text, ScreenTip:=””, TextToDisplay:=Selection.Text
‘Selection.Collapse Direction:=wdCollapseEnd
Loop While (Selection.Font.Superscript = True)
结果,
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:=””, SubAddress:=”_” & Selection.Text, ScreenTip:=””, TextToDisplay:=Selection.Text
所实现的功能,的确是添加了页内链接了,但是Ctrl+点击该文字后,光标却跳转到文档开头了,而不是跳转到对应的标题位置。
【尝试解决的过程】
1.而自己手动去设置页内跳转的链接,是可以工作的,但是却无法看到其所添加的链接地址是多少,所以没法继续。
2.百度google了很多,发现别人也有在excel中遇到类似问题,用SubAddress添加的业内链接无效。但是没看到有效解决办法。
3.以为是新装的office 2010的问题,所以卸载了office 2010,换上旧的office 2003,重新尝试,问题依旧。