PDA

View Full Version : Save formfield data for specific section only



hippy
12-15-2008, 01:52 PM
I have a form [9 sections] with form fields for creating a final report from risk assessments. To create an executive summary I would like to only capture form field data from sections 3 & 4.

SO far I am able to get all form field data to text no worry; but I can not work out how if at all possible to only form field data from section 3 & 4 only.
Any help would be appreciated.

fumei
12-15-2008, 02:26 PM
Three possible ways.

1. Use the names of the formfields in those sections.

2. Use formfield objects and loop through just those Sections.
Sub Just3_4()
Dim oFF As FormField
Dim DocFF As FormFields
Dim j As Long
Dim msg As String

For j = 3 To 4
Set DocFF = ActiveDocument.Sections(j).Range.FormFields
For Each oFF In DocFF
msg = msg & oFF.Result & vbCrLf
Next
Next
MsgBox msg
End Sub


3. Make a Range object of just those sections, and loop through the formfields of that range.

Sub WithRange()
Dim r As Range
Dim oFF As FormField
Dim msg As String

Set r = ActiveDocument.Range(Start:=ActiveDocument.Sections(3) _
.Range.Start, _
End:=ActiveDocument.Sections(4) _
.Range.End)
For Each oFF In r.FormFields
msg = msg & oFF.Result & vbCrLf
Next
MsgBox msg
End Sub


Demo attached for both #2 and # 3.

Click "Using Sections" on the top toolbar to execute #2 code.

Click "Using Range" to execute #3 code.

They both return the same thing....an appended string of the text formfields in ONLY Section 3 and Section 4.

fumei
12-15-2008, 02:36 PM
Just as a BTW....I believe #3 (making a range of both sections) is technically more efficient, and possibly faster. That is because #2 uses two separate For Each loops (one for each section).

Note that you can NOT ever make a non-contiguous range. In other words you can not make a range object of Section 3 and Section 5 (skipping Section 4). Mind you, you can not do that with a For j = loop either.

If you wanted to action non-contiguous Sections, you would have to make an array.

Dim mySections()
Dim j as Long
mySections = Array(3, 5, 6, 9)

For j = 0 To Ubound(mySections())
Set DocFF = ActiveDocument.Sections(mySections(j)) _
.Range.FormFields
For Each oFF In DocFF
msg = msg & oFF.Result & vbCrLf
Next

would action the formfields in Sections 3, 5, 6, 9.

hippy
12-15-2008, 02:51 PM
Many Thanks Fumei. I have not used yet. I have have to head off to work now. Will set up for option 3 at work and run.