Paul, sometimes you make me feel dumb.
Paul, the first suggestion did not seem to work...seems it does not recognize the last paragraph mark....so I made the suggested substitution.
Unfortunately, it threw an error code.
Run-time error '91'
Object variable or With block variable not set
when I went to the debug screen the following was highlighted.
Set Rng = Rng.Characters.Last
The complete code is below.
Option Explicit
Dim FSO As Object, oFolder As Object, StrFolds As String, wdDocSrc As Document, wdDocTgt As Document
Sub ReplaceParagraphsInHeader()
Application.ScreenUpdating = False
Dim TopLevelFolder As String, TheFolders As Variant, aFolder As Variant, i As Long
TopLevelFolder = GetFolder
If TopLevelFolder = "" Then Exit Sub
StrFolds = vbCr & TopLevelFolder
If FSO Is Nothing Then
Set FSO = CreateObject("Scripting.FileSystemObject")
End If
Set wdDocSrc = ActiveDocument
'Get the sub-folder structure
Set TheFolders = FSO.GetFolder(TopLevelFolder).SubFolders
For Each aFolder In TheFolders
RecurseWriteFolderName (aFolder)
Next
'Process the documents in each folder
For i = 1 To UBound(Split(StrFolds, vbCr))
Call UpdateDocuments(CStr(Split(StrFolds, vbCr)(i)))
Next
Set wdDocSrc = Nothing: Set wdDocTgt = Nothing
Application.ScreenUpdating = True
End Sub
Sub RecurseWriteFolderName(aFolder)
Dim SubFolders As Variant, SubFolder As Variant
Set SubFolders = FSO.GetFolder(aFolder).SubFolders
StrFolds = StrFolds & vbCr & CStr(aFolder)
On Error Resume Next
For Each SubFolder In SubFolders
RecurseWriteFolderName (SubFolder)
Next
End Sub
Function GetFolder() As String
Dim oFolder As Object
GetFolder = ""
Set oFolder = CreateObject("Shell.Application").BrowseForFolder( 0, "Choose a folder", 0)
If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.path
Set oFolder = Nothing
End Function
Sub UpdateDocuments(oFolder As String)
Dim strInFolder As String, strFile As String, Sctn As Section, HdFt As HeaderFooter, Rng As Range
strInFolder = oFolder
strFile = Dir(strInFolder & "\*.doc", vbNormal)
While strFile <> ""
Set wdDocTgt = Documents.Open(FileName:=strInFolder & "" & strFile, AddToRecentFiles:=False, Visible:=False)
With wdDocTgt
For Each Sctn In .Sections
For Each HdFt In Sctn.Headers
With HdFt
If .Exists Then
Set Rng = Rng.Characters.Last
With Rng
Do While .Characters.First.Previous = vbCr
.Start = .Start - 1
Loop
If .Paragraphs.Count > 2 Then .Text = vbCr & vbCr
End With
End If
End With
Next
Next
'Save and close the document
.Close SaveChanges:=True
End With
strFile = Dir()
Wend
End Sub
|