

Java技术
2005: 03 04 05 06 07 08
09 10 11 12
2006: 01 02
Asp.net
2005: 07 08 09 10 11 12
2006: 01 02

本文将告诉你如何使用VB代码连接Office应用程序,并简要接触一下在文件中输入数据的方法。实际上,在VB中用代码与Word和Excel进行会话并控制它们,是可行的。但是请注意,首先需要在机器上安装office应用程序,才能在VB代码中存取它们的对象。 | ||
下面就是一些例子,告诉你如何与这些程序会话,并控制它们。
Option Explicit Dim xlsApp As Excel.Application Dim wrdApp As Word.Application只要相关的对象库已经被选择,在应用程序中进行对象变量的赋值是可能的。Microsoft Excel 8.0对象库是相对于Excel的,而 Microsoft Word 8.0 对象库是为Word服务的。
在VB的IDE环境中,从“工程”菜单中选择“引用”,可以看到系统可用的所有库列表。
Private Sub Command1_Click() Set xlsApp = Excel.Application With xlsApp ´Show Excel .Visible = True ´Create a new workbook .Workbooks.Add ´Put text in to the cell that is selected .ActiveCell.Value = "Hi" ´Put text into A3 regardless of the selected cell .Range("A3").Value = "This is an example of connecting to Excel" End With End Sub在上面的程序段中,我们在变量xlsApp中建立了一个对象,这样Excel就对用户可见了。当Excel象这样启动后,并不包含一个工作簿,所以必须创建或者执行打开操作。这里,我们建立了一个新的工作簿,然后,就可以操作其中的信息,或者打印,或者保存,或者你任意想做的事情。
Private Sub Command2_Click() ´close the workbook xlsApp.Workbooks.Close ´Close Excel xlsApp.Quit End Sub上面这段代码执行关闭程序的功能。首先,关闭工作簿,这将出现一个提示对话框,询问用户是否想保存修改;然后,退出应用程序。
Private Sub Command3_Click() Set wrdApp = New Word.Application With wrdApp ´Show Word .Visible = True ´Create New Document .Documents.Add ´Add text to the document .ActiveDocument.Content.Text = "Hi" .ActiveDocument.Content.Text = "This is a test example" End With End Sub上面这段代码中,在变量wrdApp中设置引用Word程序的对象。同样,当Word按照这种方式启动后,不会包含一个文档,所以,必须执行建立或者打开操作。这里是建立了一个新文档,然后可以操作其中的信息了,打印、保存、发送邮件,等等...
但是,在Word文档中放置文本并非容易!特别是与Excel一起工作时。为了简单地在特定的地方放置文本,需要有一个bookmark标记。这意味着,需要事先建立一个模板。
Private Sub Command4_Click() ´Close the current document wrdApp.ActiveDocument.Close ´Close Word wrdApp.Quit End Sub上面这段代码的功能是关闭应用程序。首先,关闭当前文档,这时可能需要用户保存修改。然后,退出程序。
Private Sub Form_Unload(Cancel As Integer) ´Clear the memory Set xlsApp = Nothing Set wrdApp = Nothing End Sub最后一段代码就是关闭VB应用程序。这是优秀程序员编程的好习惯。
Well I hope this brief tutorial is helpful. It does not touch on much of what you can do to the office applications once they´re open, but should give you an idea of how to get started.
好了,简单的介绍到此结束。我希望能抛砖引玉,让你更加随意地操作Office应用程序!