Reputation: 155588
I'm trying to insert a series of Word fields based on the content of a simple text file, however when I run this code it inserts all of the fields together and clumps all of the linebreaks after all of the fields instead of inserting a linebreak in-between each field. Pray tell, what am I doing wrong?
Option Explicit
Sub AddFields()
Dim fileName As String
fileName = InputBox("Filename containing field list")
Dim fso As New Scripting.FileSystemObject
Dim fileStream As Scripting.TextStream
Set fileStream = fso.OpenTextFile(fileName, ForReading, False)
Dim line As String
While Not fileStream.AtEndOfStream
line = fileStream.ReadLine
Selection.Range.InsertBreak WdBreakType.wdLineBreak
AddField line
Wend
End Sub
Sub AddField(mergeFieldName As String)
Dim fieldText As String
fieldText = "MERGEFIELD " & mergeFieldName & " "
ActiveDocument.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:=fieldText, PreserveFormatting:=False
End Sub
Upvotes: 0
Views: 912
Reputation: 2865
I can't find a good explanation as well.
Both of these work if you put them instead of your InsertBreak line:
Selection.InsertBreak WdBreakType.wdTextWrappingBreak
Selection.TypeParagraph
The first has a slightly different meaning (see http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.wdbreaktype(v=office.14).aspx) but it looks OK in the context of your script. The second one is what word does when I record a macro and type text
Upvotes: 1