An About Visual Basic reader wanted to know how to add a button to a form that would score a test he had created as a Word document. The work that had been done already was pretty impressive, but he had only used FORMDROPDOWN field codes so far.
This isn't a Word tutorial, but to get the most from the VBA macro coding, you need to understand what it's based on. Here's the way one question from the document had been written. And, I'm using Word 2007. You can do the same thing in earlier versions, but the interface looks quite different.
--------
Click Here to display the illustration
Click the Back button on your browser to return
--------
There are some things that you just can't do without a little programming. Scoring the test based on the selections in these FORMDROPDOWN fields is one of them.
To get started, select the Developer tab in the Word 2007 ribbon. (You might have to click the Office Button and select Word Options to display the Developer tab. See the illustration to see what that looks like.)
--------
Click Here to display the illustration
Click the Back button on your browser to return
--------
Add a Button and some Label controls to trigger the execution of the VBA macro and display the results.
--------
Click Here to display the illustration
Click the Back button on your browser to return
--------
Now the fun starts. Double click the Button to open the VBA code window. I'll just show the code now and explain it later.
Private Sub btnScoreTest_Click()
Application.Visible = False
'Application.ScreenUpdating = False
'Question 1
If (ActiveDocument.FormFields("Q1").Result) = "True" Then
TotalScore = TotalScore + 1
End If
'Question 2
If (ActiveDocument.FormFields("Q2").Result) = "A)" Then
TotalScore = TotalScore + 1
End If
'
' .... and so forth. The rest of the questions aren't shown
'
'Display Score
Application.Visible = True
'Application.ScreenUpdating = True
lblStudentName.Caption = _
ActiveDocument.FormFields(1).DropDown.ListEntries( _
ActiveDocument.FormFields(1).DropDown.Value).Name
lblStudentScore.Caption = TotalScore
End Sub
Application.Visible = False is there to prevent the document from jumping all over as the rest of macro is executed. Many programmers prefer to use Application.ScreenUpdating instead. If nothing is coded, then Word adjusts the position of the document as each field code is referenced and it can be slightly disconcerting to watch. Besides, it slows everything down.
My reader had not coded any Bookmark values in the field code dialog. If you don't use Bookmark values, then you have to reference each field code by the index value of the position in the document. Using Bookmark values is better.

