在上面的程序段中,我们在变量xlsApp中建立了一个对象,这样Excel就对用户可见了。当Excel象这样启动后,并不包含一个工作簿,所以必须创建或者执行打开操作。这里,我们建立了一个新的工作簿,然后,就可以操作其中的信息,或者打印,或者保存,或者你任意想做的事情。
! Z4 f/ O: n- F9 A% ] Private Sub Command2_Click()
- \& F9 U' {! j) e' Z 'close the workbook
9 X k- [% W# D* {1 I xlsApp.Workbooks.Close1 E4 _. P* D% a
'Close Excel# ?! H& f& |- y2 [/ M: H) n
xlsApp.Quit
3 T& L/ P; s, [ End Sub
6 D0 {1 `4 v6 i; V 上面这段代码执行关闭程序的功能。首先,关闭工作簿,这将出现一个提示对话框,询问用户是否想保存修改;然后,退出应用程序。
7 J5 H% f2 X" ?) I Private Sub Command3_Click()
$ |1 c1 W' a6 F0 v! k' s: | Set wrdApp = New Word.Application% i1 D: \; g1 x4 g$ W( U/ M3 F2 p
With wrdApp
; h2 b% h! h' C& Z3 y- [ 'Show Word
4 ] Z3 S5 }& b5 j% N6 | .Visible = True8 x' x% U! X1 M6 u
'Create New Document
$ B' R) l; E& x( M .Documents.Add
9 Z, y3 R# R: ~- c5 ^5 R7 j 'Add text to the document
, M" Y$ Q1 @, \8 t .ActiveDocument.Content.Text = "Hi"$ A" T" v9 _( c2 R& M4 R. e8 G
.ActiveDocument.Content.Text = "This is a test example"
/ t6 U4 \" T. N" L/ v End With
& E% |; a) O8 I$ N6 `1 P/ n5 C( A End Sub
0 N9 z! X) u$ W; ]% R" w' Z 上面这段代码中,在变量wrdApp中设置引用Word程序的对象。同样,当Word按照这种方式启动后,不会包含一个文档,所以,必须执行建立或者打开操作。这里是建立了一个新文档,然后可以操作其中的信息了,打印、保存、发送邮件,等等..., b6 c0 H) ?! f& D+ h
但是,在Word文档中放置文本并非容易!特别是与Excel一起工作时。为了简单地在特定的地方放置文本,需要有一个bookmark标记。这意味着,需要事先建立一个模板。
. B: q; p1 \) _& L3 l J3 H Private Sub Command4_Click()! @, Q5 ]' p8 V2 U: H, k
'Close the current document
# b# \" X6 a% h% B+ Z+ c wrdApp.ActiveDocument.Close9 P* ` f9 c$ v2 `. k
'Close Word# o' w6 p5 B( ?4 y" W% H: X! k
wrdApp.Quit# |% x6 e# _7 o$ n
End Sub2 V- e+ E! l/ v- [
上面这段代码的功能是关闭应用程序。首先,关闭当前文档,这时可能需要用户保存修改。然后,退出程序。8 B# {: t8 E. f
Private Sub Form_Unload(Cancel As Integer)
! e; o G/ N k3 `1 y3 t 'Clear the memory+ ^* z9 y+ M/ x% q
Set xlsApp = Nothing3 s! P" ]! I% N V" {. ]+ ]
Set wrdApp = Nothing
- I! e* d/ a% x8 k: l End Sub5 e4 R% \0 u/ x! \2 C5 X
最后一段代码就是关闭VB应用程序。这是优秀程序员编程的好习惯。
! g0 [2 U2 u1 b" G/ _! i 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. |