I'm having trouble with adding a header only to the first page of a Word document. Here is the code; the header appears on every page from a second page in the Word document. How can I change it so the header would only be on the first page of a Word document?
Here is the code:
Sub CreateWordFileFromExcel()
Dim wordApp As Object
Dim wordDoc As Object
Dim filePath As String
Set wordApp = CreateObject("Word.Application")
wordApp.Visible = True
Set wordDoc = wordApp.Documents.Add
desktopPath = Environ("USERPROFILE") & "\Desktop\"
filePath = desktopPath & "TemplateMEMO.docx" ' Replace this with your desired file path and name"
ThisWorkbook.Sheets("1").UsedRange.Copy
Dim headerRange As Object
Set headerRange = wordDoc.Sections(1).Headers(1).Range
headerRange.Text = "Company name" & vbCr & _
"Address" & vbCr & _
"City" & vbCr & _
"Country" & vbCr & _
"Tel: +7 (727) 777 77 77" & vbCr & _
"Fax: +7 (727) 888 88 88" & vbCr & _
"company website"
headerRange.ParagraphFormat.Alignment = 2
headerRange.Font.Size = 9
wordDoc.PageSetup.DifferentFirstPageHeaderFooter = True
Dim section As Object
For Each section In wordDoc.Sections
If section.Index > 1 Then
section.Headers(1).Range.Text = ""
End If
Next section
wordApp.Selection.Collapse Direction:=0 ' 0 for collapse to the end of the range
ThisWorkbook.Sheets("2").UsedRange.Columns.AutoFit
wordDoc.Range.PasteExcelTable LinkedToExcel:=False, WordFormatting:=False, RTF:=False
wordDoc.SaveAs filePath
Set wordDoc = Nothing
Set wordApp = Nothing
Set headerRange = Nothing
Set logoShape = Nothing
End Sub
I already tried this:
wordDoc.PageSetup.DifferentFirstPageHeaderFooter = True Dim section As Object For Each section In wordDoc.Sections If section.Index > 1 Then section.Headers(1).Range.Text = "" End If Next section
And this:
wordDoc.PageSetup.DifferentFirstPageHeaderFooter = True Dim section As Object For Each section In wordDoc.Sections If section.Index > 1 Then section.Headers(1).Range.Delete End If Next section
and this:
wordApp.Selection.InsertBreak Type:=7 ' (since I have 7 pages) Dim section As Object For Each section In wordDoc.Sections If section.Index > 1 Then section.Headers(1).Range.Delete End If Next section