Simple Migration of a Word VBA Project

In this section, you will migrate a sample Word VBA application to VSTO. As shown in Figure 12.1, the application is a simple memo template that prompts users for information when they create a new document. After users enter information into the fields of the VBA UserForm and click OK, the bookmarks on the document are populated with the information.

The New event fires when a new document is created from a template. It is here that you will write the code to show the UserForm, because the form is displayed only when the document is created. You also set other properties of the document, such as the caption. The frmMain.Show code in Listing 12.1 displays the UserForm in Figure 12.1.

Listing 12.1. Displaying a UserForm when a new document is created Private Sub Document_New()

With ActiveDocument

.SpellingChecked = True .GrammarChecked = True .ActiveWindow.Caption = _

.ActiveWindow.Caption & " - Memo" .ActiveWindow.View.ShowFieldCodes = False End With

' Show the form. frmMain.Show End Sub

&pb &fct fart Format lods tsfttc üinaw Hdp

■■fa Retj Ii AdiS es; » -5 B Q ^

If - .¿i&«HJ 1

;L . , . . ' Ù, ' -

», «

„ -


C* J



Tb: To Fielc From: From Fielc CC: CC Fielc Date: July 4. 2006 Ret Re Fielc

1 SSI lfl AiQ.T li-1 cd l

"-•;?: ¡¡XT Erçfefc<U.S /

Figure 12.1. Word VBA application with input form

Figure 12.2 shows the UserForm in the design view of the VBA Editor.

As shown in Listing 12.2, the VBA code handled by the Click event of the OK button sets the text box values to the correct bookmark and then closes the form.

Figure 12.2. Input form in the VBA Editor

Listing 12.2. Populating bookmarks on a UserForm Click event Private Sub btnOK Click()

' Insert the fields into the bookmarks. With ActiveDocument

.Bookmarks("To").Range = txtTo .Bookmarks("From").Range = txtFrom .Bookmarks("CC").Range = txtCC .Bookmarks("Re").Range = txtRe .Bookmarks("Subject").Range = txtSubject End With

Unload Me End Sub

Figure 12.3 shows the expected results of your VBA project. The bookmarks have been populated with the correct information from your UserForm.

|S| Document2 - Memo

ffff Inl vl

File Edit View Insert Format Tools Table Window Help - X

JESidBfll^til^ia -.-ids./ "> - 4,3 IT - IBee»d i

^ Return Addres:

rial - 8 - H I U — !" g . "t? . A - B

; j . . . , . . 2]


To: Paul

From: Kathleen

CC: Mike

Date: July 4, 2006

Re: Everyone

VBA Migration


Type memo body here.

= a[s] 5 Eg ' 1


Page 1 Sec 1

VI At O.T Ln 1 Col 1 REC TRK EfT 0\ R English {U,S J

Figure 12.3. Completed Word VBA application

Figure 12.3. Completed Word VBA application

0 0

Post a comment