Tuesday, 3 September 2013

Excel headers/footers won't change via VBA unless blank

Excel headers/footers won't change via VBA unless blank

Disclaimer: It's been a few years since I worked (a lot) with VBA, so this
might be an issue caused by confusing myself with what is essentially a
very different language from what I usually deal with.
So; I've got a workbook (Excel 2010) with multiple sheets (20+), most of
whom are multi-page. To make things easier when printing everything, I
want to add some sheet-specific headers with amongst others the name of
the sheet, number of pages and so on.
I've written a tiny function that should (in theory) do this for me by
iterating over all the sheets setting the header. However, for some reason
it only works if the header is empty; if it already has a value it refuses
to overwrite for some unknown reason.
Dim sheetIndex, numsheets As Integer
sheetIndex = 1
numsheets = Sheets.Count
' Loop through each sheet, but don't set any of them to active
While sheetIndex <= numsheets
Dim sheetname, role, labeltext As String
sheetname = Sheets(sheetIndex).name
role = GetRole(mode)
labeltext = "Some text - " & sheetname & " - " & role
With Sheets(sheetIndex).PageSetup
.LeftHeader = labeltext
.CenterHeader = ""
.RightHeader = "Page &[Page] / &[Pages]"
.LeftFooter = "&[Date] - &[Time]"
.CenterFooter = ""
.RightFooter = "Page &P / &N"
End With
sheetIndex = sheetIndex + 1
Wend

No comments:

Post a Comment