Having far too much time on my hands today and having created all those
variables in the document, a quick and easy means of inserting the
associated fields in the document would not be a bad idea so the following
macro will do that. Each time it is run it inserts the next numbered
docvariable field at the cursor (so run it from a toolbar button of keyboard
shortcut). It requires a further mod to Peter's macro, which is included
that counts the available fields and prevents the user from adding more
docvariable fields than he has docvariables. Re-run that macro if necessary
to add the extra variable that stores the count.
Sub InsertLineVariable()
Dim oVars As Variables
Dim vVar As Variant
Dim aNum As Integer
Dim bNum As Integer
Dim bExists As Boolean
Dim varExists As Boolean
Set oVars = ActiveDocument.Variables
bExists = False
varExists = False
For Each vVar In oVars
If vVar.name = "numVars" Then
varExists = True
Exit For
End If
Next vVar
For Each vVar In oVars
If vVar.name = "varCount" Then
bExists = True
Exit For
End If
Next vVar
If varExists = False Then
MsgBox "There are no variables in the document" & _
" associated with this macro", vbCritical, "Error"
Exit Sub
End If
If bExists = False Then
oVars("varCount").Value = 0
End If
oVars("varCount").Value = oVars("varCount").Value + 1
aNum = oVars("varCount").Value
bNum = oVars("numVars").Value
If aNum > bNum Then
MsgBox "There are no more variables to insert", _
vbInformation, "Insert Variables"
Exit Sub
End If
Selection.Fields.Add Selection.Range, _
wdFieldDocVariable, "line" & _
oVars("varCount").Value, False
End Sub
Sub TransferTextRowsToVariables()
Dim iCount As Integer
Dim strLine As String
Dim bExists As Boolean
Dim vVar As Variant
Dim oVars As Variables
Set oVars = ActiveDocument.Variables
bExists = False
For Each vVar In oVars
If InStr(1, vVar.name, "line") Then
vVar.Delete
End If
Next vVar
' use your file name here
Open "D:\My Documents\Test\Versions\filename.txt" For Input As 1
iCount = 0
While Not EOF(1)
Line Input #1, strLine
iCount = iCount + 1
On Error Resume Next
'ActiveDocument.Variables("line" & iCount).Delete
Err.Clear
On Error GoTo 0
If Len(strLine) <> 0 Then
oVars.Add "line" & iCount, strLine
Else
iCount = iCount - 1
End If
Wend
Close #1
'MsgBox "Variables line1 to line" & iCount & " created"
For Each vVar In oVars
If vVar.name = "numVars" Then
bExists = True
oVars("numVars").Value = iCount
Exit For
End If
Next vVar
If bExists = False Then
oVars.Add "numVars", iCount
End If
End Sub
--
<>>< ><<> ><<> <>>< ><<> <>>< <>><<>
Graham Mayor - Word MVP
My web site
www.gmayor.com
<>>< ><<> ><<> <>>< ><<> <>>< <>><<>