[VB.NET]轻松控制Word

来源:互联网 发布:通州淘宝城关了吗 编辑:程序博客网 时间:2024/04/30 22:49
轻松控制Word

实例说明

在本实例中,我们将制作一个能够控制Word文件的建立和打开的应用程序。我们可以在文本框中输入文件名,单击"新建"按钮即可新建一个Word文档,或者打开一个Word历史记录文件。程序运行结果如图75-1所示。

图75-1 运行结果

技术要点

l 添加Word库引用

<script type="text/javascript"><!--google_ad_client = "pub-8333940862668978";/* 728x90, 创建于 08-11-30 */google_ad_slot = "4485230109";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

l 建立Word对象

l 读取Word历史记录文件

实现过程

■ 新建项目

打开Visual Studio.NET,选择"新建项目",在项目类型窗口中选择"Visual Basic项目",在模板窗口中选择"Windows应用程序",在名称域中输入"ControlWord",然后选择保存路径。单击"确认"。

■ 添加引用和控件

选择菜单"项目|添加引用",在弹出的"添加引用"对话框中选择COM选项卡,选中"Microsoft Word 10.0 Object Library",单击"选择"按钮,即可将Word库加入到当前项目中。添加时的界面如图75-2所示。然后,给窗体上添加两个Label控件和两个Button控件,一个TextBox控件和一个ComboBox控件。

图75-2 添加Word引用

■ 设置属性

对窗体上的控件设置属性,如表75-1所示。

表75-1 窗体及控件的属性值

窗体/控件 属性 值

Form1 Text 轻松控制Word

TextBox1 Text 空

ComboBox Text 空

Button1 Text 新建

■ 添加代码

Public Sub New()

MyBase.New()

'程序启动时,添加Word历史记录文件

'This call is required by the Windows Form Designer.

InitializeComponent()

Dim i As Short

Dim tempword As New Word.Application()

For i = 1 To tempword.RecentFiles.Count

ComboBox1.Items.Add(tempword.RecentFiles.Item(i).Name)

Next

'ComboBox1.Text = ComboBox1.Items.IndexOf(ComboBox1).ToString

'combobox1.Items.GetTy

tempword.Quit()

'Add any initialization after the InitializeComponent() call

End Sub

'打开word文件

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim b As New Word.Application()

b.Documents.Open(ComboBox1.Text)

b.Visible = True

End Sub

'新建word文件

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

Dim word As New Word.Application()

word.NewDocument.Add(TextBox1.Text)

word.Visible = True

End Sub

■ 运行程序

单击菜单"调试|启动"或单击 图标运行程序。

小结

本实例我们先引用了Word库,然后新建Word对象,这样就可以实现与Word的连接了。其余对象的引用类似。

原创粉丝点击