| VBA - Word and Excel Working Together | |||||||||||||||||||||||
| Part 4: The Word Form | |||||||||||||||||||||||
The next thing to do is to design and build the form frmDocPhrases and start writing code for it. Here's what the form looks like:
There are six bookmarks in the document and each one is updated by a command button. The top four display a listbox selection and the bottom two simply update from the Excel workbook. Earlier, I mentioned that it's probably not a good design choice to place controls into the Word document. The problem is that when you place controls into the document, they're actually Word fields and they have all the limitations (and some advantages) that fields have. In our application, for example, we have placed all the listboxes in the same space on the form and then simply made only one visible at a time. A listbox inside a Word document doesn't even have a Visible property and there is no way to place them in the same space in the document. Here's what the VBA code in the Click event for each of the top four buttons looks like:
This code above is for the Salutation command button. The other three are very similar, but this one has a key difference. To be able to call the first command button subroutine from the document VBA code, we have to make a change in the way the initial subroutine code is automatically entered for us by the Visual Basic editor. The editor automatically creates an empty default subroutine: Private Sub cmdSal_Click() End Sub Change the Private to Public or the code in the Document_Open() subroutine in the Word document won't be able to locate the subroutine in the frmDocPhrases form code since they're in different modules. This is true even though they're stored in the same file (the Word document). This is a good example of the concept of "scope" in Visual Basic programming. When an item in the listbox is clicked, the text in the item is inserted into the Word document using this code: Private Sub lstSal_Click()
Selection.TypeText (lstSal.Text)
End Sub
And the final "Word only" subroutine is simply an internal utility Sub to avoid repeating identical lines of code in several places. Private Sub HideListBoxes()
lblListBoxTitle.Caption = ""
lstSal.Visible = False
lstAgent.Visible = False
lstAgentAction.Visible = False
lstCondition.Visible = False
End Sub
Next page >
VBA Code Calling the Excel Server > Page
1,
2,
3,
4
5,
6
|
|||||||||||||||||||||||



