多语言展示
当前在线:355今日阅读:23今日分享:25

word文档添加返回目录悬浮按钮的方法

利用VBA给word文档添加一个悬浮按钮,只需鼠标单击该按钮就能跳转回文档的目录。
工具/原料
1

word2003

2

vba

方法/步骤
1

ALT+F11打开VBE编辑器,在工程窗口右键-插入-用户窗体,插入一个新窗体UserForm1。

2

在窗体属性对话框将:ShowModel属性设为False即将窗体设为无模态窗体,BorderStyle属性设为0-fmBorderStyleNone即将窗体设为无边框,StartUpPosition属性设为0-手动即将窗体的初始显示位置设置成手动更改,其余属性请按需更改。

3

利用标签控件在窗体上拖拉出一个标签Label1。

4

将标签Label1的Caption属性设为返回目录,BorderStyle属性设为0-fmBorderStyleNone,其余属性按需设置即可。

5

在窗体UserForm1代码窗口粘贴入下代码:Private Declare Function GetWindowLong Lib 'user32' Alias 'GetWindowLongA' (ByVal hWnd As Long, ByVal nIndex As Long) As LongPrivate Declare Function SetWindowLong Lib 'user32' Alias 'SetWindowLongA' (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As LongPrivate Declare Function FindWindow Lib 'user32' Alias 'FindWindowA' (ByVal lpClassName As String, ByVal lpWindowName As String) As LongPrivate Declare Function DrawMenuBar Lib 'user32' (ByVal hWnd As Long) As LongPrivate Declare Sub ReleaseCapture Lib 'user32' ()Private Declare Function SendMessage Lib 'user32' Alias 'SendMessageA' (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As LongPrivate Const GWL_STYLE As Long = (-16)Private Const WS_CAPTION As Long = &HC00000Private Const WM_NCLBUTTONDOWN = &HA1Private Const HTCAPTION = 2Private Sub Label1_Click()Selection.HomeKey unit:=wdStory '返回文档开头Selection.MoveDown unit:=wdLine, Count:=9 '笔者此处演示文档,目录位置是位于文档开头往下数9行,具体可以根据需要自行更改End SubPrivate Sub UserForm_Initialize()    Dim lngStyle As Long    Dim hWnd As Long    hWnd = FindWindow(vbNullString, Me.Caption)    lngStyle = GetWindowLong(hWnd, GWL_STYLE)    SetWindowLong hWnd, GWL_STYLE, lngStyle And Not WS_CAPTION    DrawMenuBar hWnd    Me.Height = 31.5    Me.Left = Selection.Information(wdHorizontalPositionRelativeToPage) + 545    Me.Top = Selection.Information(wdVerticalPositionRelativeToPage) + 50End SubPrivate Sub Label1_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)    Dim hWnd As Long    hWnd = FindWindow(vbNullString, Me.Caption)    ReleaseCapture    SendMessage hWnd, WM_NCLBUTTONDOWN, HTCAPTION, 0&End Sub

6

在ThisDocument代码窗口粘贴如下代码:Private Sub Document_Open()UserForm1.ShowEnd Sub

注意事项

将代码Selection.MoveDown unit:=wdLine, Count:=9中的数字9更改为你需要跳转到的行即可。

推荐信息