使用 vb 6 和 vb.net 为 Office 应用添加工具栏和按钮
在 Office 应用中,有可我们可能需要利用 word 进行一系列的操作,比如执行一段宏,通过点击一个工具栏按钮执行宏的代码段,下面的实例正是为 office 应用添加一个工具栏和按钮,类似可应用到 excel 和 aceess 等 Office 应用程序。
** 1. ** ** 在 VB6 ** ** 中的应用: **
在 VB6 中引用 Micosoft Word X.0 (版本号) Object Library 和 Micosoft Office X.0 (版本号) Object Library ,如下图:(笔者使用 Office XP )
添加如下代码:
Private Sub Command1_Click()
' 定义 word 应用
Dim wordApp As New Word.Application
Dim myDoc As Word.Document
' 定义工具栏
Dim myBar As Office.CommandBar
' 定义工具栏按钮
Dim myButton As Office.CommandBarButton
Dim IsExist As Boolean
IsExist = False
' 打开一个 word 文档
Set myDoc = wordApp.Documents.Open("f:\test.doc")
wordApp.Visible = True
' 如果存在这个工具栏,就显示这个工具栏
For Each myBar In wordApp.CommandBars
If myBar.Name = " 文件操作 " Then
myBar.Visible = True
IsExist = True
End If
Next
' 如果不存在 , 就创建工具栏及按钮
If Not IsExist Then
Set myBar = wordApp.CommandBars.Add( _
Name:=" 文件操作 ", _
Position:=msoBarTop, _
Temporary:=False)
Set myButton = CommandBars(" 文件操作 ").Controls.Add
With myButton
.Caption = " 文件保存 "
.ToolTipText = "lihonggen create"
' .Picture =LoadPicture("f:\cd.ICO")
' 指定表面图片序号
.FaceId = 10
.Visible = True
.Enabled = True
' 指定此按钮宏的名称
.OnAction = "lihonggen"
End With
myBar.Visible = True
End If
End Sub
** 2. ** ** 在 VB.NET ** ** 中的应用: **
同样,需要添加 Micosoft Word X.0 (版本号) Object Library 和 Micosoft Office X.0 (版本号) Object Library 这两个对象库的引用
Private Sub Button1_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' 定义 word 应用
Dim wordApp As New Word.Application()
Dim myDoc As Word.Document
' 定义工具栏
Dim myBar As Microsoft.Office.Core.CommandBar
' 定义工具栏按钮
Dim myButton As Microsoft.Office.Core.CommandBarButton
Dim isExist As Boolean
isExist = False
' 打开一个 word 文档
myDoc = wordApp.Documents.Open( "f:\test.doc" )
wordApp.Visible = True
' 如果存在这个工具栏,就显示这个工具栏
For Each myBar In wordApp.CommandBars
If myBar.Name = " 文件操作 " Then
myBar.Visible = True
isExist = True
End If
Next
' 如果不存在 , 就创建工具栏及按钮
If Not isExist Then
myBar = wordApp.CommandBars.Add( _
Name:= " 文件操作 " , _
Temporary:= False )
myButton = myBar.CommandBars( " 文件操作 " ).Controls.Add
With myButton
.Caption = " 文件保存 "
.TooltipText = "lihonggen create"
' 指定图片序号
.FaceId = 10
.Visible = True
.Enabled = True
' 指定此按钮宏的名称
.OnAction = "lihonggen"
End With
myBar.Visible = True
End If
End Sub
在 word 中录制的宏:
生成的工具栏及按钮:
宏的运行结果:
读者可以在写基础上进行扩展!
--------------------------------------------------------------------------
Author : lihonggen0
个人专栏: http://www.csdn.net/develop/author/netauthor/lihonggen0/
如需引用,请指明出处!软件的目的在于应用,本文可自由转载!
--------------------------------------------------------------------------