I have got a document that uses the same footer for all pages but I want to change the layout and have different footer on the first page and all the rest of the pages.
Sadly I have no clue how to change the footer. I think I have to use two different footer but where do I address the correct page?
Public Sub footer()
Set p_image = ActiveDocument.Shapes.AddPicture(FileName:= _
p_path & "BwK_" & INIT.p_CO & "_XX_XX_FL_2020.jpg", _
LinkToFile:=True, _
SaveWithDocument:=False, _
Width:=MillimetersToPoints(170), _
Height:=MillimetersToPoints(20), _
Anchor:=ActiveDocument.Sections(1).Headers(wdHeaderFooterFirstPage).Range)
With p_image
.RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
.Left = MillimetersToPoints(20)
.RelativeVerticalPosition = wdRelativeVerticalPositionPage
.Top = MillimetersToPoints(275)
End With
End Sub
The following will set all sections in a document to have a different first page for headers AND footers.
Sub HeaderFirstPageOn()
' Charles Kenyon 2021-12-29
' Set Different First Page for Headers and Footers in all sections
Dim iSections As Long
Dim iCount As Long
Let iSections = ActiveDocument.Sections.Count
For iCount = 1 To iSections
Let ActiveDocument.Sections(iCount).PageSetup.DifferentFirstPageHeaderFooter = True
Next iCount
End Sub
Here is a macro that sets this for the first section only.
Sub HeaderFirstPageOn1()
' Charles Kenyon 2021-12-29
' Set Different First Page for Headers and Footers in first section only
Let ActiveDocument.Sections(1).PageSetup.DifferentFirstPageHeaderFooter = True
End Sub
Here is a link to my writing on header and footer settings. Note that this is a Section setting, not a page or document setting and that it applies to both headers and footers. So, if you have footer content, you may need to duplicate it for the first-page header.
Thank you for your help and extensive documentation on your page, it helped me finding the correct answer:
Public Sub footer2()
Set p_image = ActiveDocument.Shapes.AddPicture(FileName:= _
p_path & "BwK_" & INIT.p_CO & "_XX_XX_FL_2022_Primary.png", _
LinkToFile:=True, _
SaveWithDocument:=False, _
Width:=MillimetersToPoints(170), _
Height:=MillimetersToPoints(20), _
Anchor:=ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range)
With p_image
.RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
.Left = MillimetersToPoints(20)
.RelativeVerticalPosition = wdRelativeVerticalPositionPage
.Top = MillimetersToPoints(275)
End With
End Sub
In fact the document only uses one section and so I only had to change wdHeaderFooterFirstPage to wdHeaderFooterPrimary.
Related
I have created this code to get my text box in the odd and even headers, but the text box is always attached to the body of the document instead of being in the header.
Dim ndx As Integer
Dim line As String
Dim lineChar As Integer
Dim pages As Integer
Dim Box As Shape
'Since the odd/even headers are different, we need to set them twice
For ndx = 1 To 2 'put back to 1 to 2
If (ActiveDocument.ActiveWindow.Panes(1).pages.Count >= ndx) Then
Selection.GoTo wdGoToPage, wdGoToAbsolute, ndx
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
Set HeaderRange = ActiveDocument.Sections.Item(1).Headers(wdHeaderFooterEvenPages).Range
HeaderRange.Text = " "
If ndx = 1 Then
Set Box = ActiveDocument.Shapes.AddTextbox( _
Orientation:=msoTextOrientationHorizontal, _
Left:=InchesToPoints(1), Top:=InchesToPoints(0.5), Width:=InchesToPoints(4.8), Height:=InchesToPoints(0.37))
Else
Set Box = ActiveDocument.Shapes.AddTextbox( _
Orientation:=msoTextOrientationHorizontal, _
Left:=300, Top:=50, Width:=500, Height:=20)
End If
Box.TextFrame.TextRange.Bold = True
Box.TextFrame.TextRange.Font.Size = 8
Box.TextFrame.TextRange.Text = "This is a sample policy from another school district. Contents do not necessarily reflect official " & _
vbCrLf & "MSBA policy, represent MSBA legal advice or service, and are not intended for exact replication."
End If
Next ndx
Thank you for your help.
Your code isn't working because it adds the text box to the document [ActiveDocument.Shapes.AddTextbox] instead of the header. The code below works for me.
Sub TextBoxInHeader()
Dim Box As Shape
Dim ndx As Integer
For ndx = 1 To 3 Step 2
With ActiveDocument.Sections(1).Headers(ndx)
.Range.Text = " "
If ndx = 1 Then 'Primary (odd pages) header
Set Box = .Shapes.AddTextbox( _
Orientation:=msoTextOrientationHorizontal, _
Left:=InchesToPoints(1), Top:=InchesToPoints(0.5), Width:=InchesToPoints(4.8), Height:=InchesToPoints(0.37))
Else 'Even pages header
Set Box = .Shapes.AddTextbox( _
Orientation:=msoTextOrientationHorizontal, _
Left:=300, Top:=50, Width:=500, Height:=20)
End If
End With
With Box.TextFrame.TextRange
.Bold = True
.Font.Size = 8
.Text = "This is a sample policy from another school district. Contents do not necessarily reflect official " & _
vbCrLf & "MSBA policy, represent MSBA legal advice or service, and are not intended for exact replication."
End With
Next ndx
End Sub
Building a Word report using vba that will include a chart. Problem is finding out how to insert chart at specific point int report. No matter what I try the chart ends up on page 1. I need it to e.g. be placed in page 2. See below for code. Works perfectly apart from chart placement
Public Function gbAuditReportGraphs(ByVal lAuditID As Long) As Boolean
'
' NRE 07-Oct-2017
'
' Purpose : Prototype graphs in Audit
' See also
' Mantis 2250
' https://msdn.microsoft.com/en-us/library/office/ff629397(v=office.14).aspx
' Note : This version outputs to a word document
' Mods
Dim objChart As chart
Dim chartWorkSheet As Excel.Worksheet
Dim rs As New ADODB.Recordset
Dim ssql As String
Dim chSeries As Series
Dim rng As Range
Dim i As Integer
Dim clsAudit_ As New clsAudit
Dim clsRig_ As New clsRig
Dim bOk As Boolean
Dim vRigName As Variant
On Error GoTo eh
' Initialise function as false
gbAuditReportGraphs = False
clsAudit_.AuditID = lAuditID
bOk = clsAudit_.mbLoad
clsRig_.RigID = clsAudit_.RigID
bOk = clsRig_.mbLoad
vRigName = clsRig_.RigName
ssql = " SELECT cl.checklistdesc" _
& " , COUNT(*) AS nccount " _
& " FROM tbltask t " _
& " , tblchecklist cl" _
& " WHERE cl.auditid=t.auditid" _
& " AND cl.checklistid = t.checklistid" _
& " AND cl.auditid = " & lAuditID _
& " AND t.tasktype = '" & gsO & "'" _
& " AND t.taskstatus>0" _
& " GROUP BY cl.checklistdesc" _
& " ORDER BY 1"
Debug.Print "modADCForms.gbAuditReportGraphs, ssql = " & ssql
' Declare the Word Application and Document
Set mobjWordApp = New Word.Application
Set mobjWordDoc = mobjWordApp.Documents.Add
mobjWordDoc.SetCompatibilityMode wdWord2010
' Add page numbers
With mobjWordDoc.Sections(1)
.Footers(wdHeaderFooterPrimary).PageNumbers.Add PageNumberAlignment:=wdAlignPageNumberRight, FirstPage:=True
'Add Date
.Footers(wdHeaderFooterPrimary).Range.InsertBefore Format(Date, "dd-MMM-YYYY") & Chr(9) & Chr(9)
.Footers(wdHeaderFooterPrimary).Range.Paragraphs.Alignment = wdAlignParagraphLeft
.Footers(wdHeaderFooterPrimary).Range.Font.Name = "ForzaMedium"
.Footers(wdHeaderFooterPrimary).Range.Font.Size = 12
End With
Debug.Print "modADCForms.gbAuditReportGraphs,0"
modADCForms.gInserttext wdStyleNormal, "Page 1", wdColorBlack
modADCForms.gInsertPage
modADCForms.gInserttext wdStyleNormal, "Page 2", wdColorBlack
Debug.Print "modADCForms.gbAuditReportGraphs 1"
Set rng = mobjWordDoc.Range
With rng
.Collapse wdCollapseEnd
.Collapse Direction:=wdCollapseEnd
.InsertParagraphAfter
.Collapse Direction:=wdCollapseEnd
End With
' Set objChart = mobjWordDoc.Shapes.AddChart(xl3DPie, , 60, , 450, rng) -- type mismatch
Set objChart = mobjWordDoc.Shapes.AddChart.chart
objChart.ChartType = xlPie
objChart.HasLegend = False
Debug.Print "modADCForms.gbAuditReportGraphs 2"
' Create chart worksheet
Set chartWorkSheet = objChart.ChartData.Workbook.Worksheets(1)
' Add a header
chartWorkSheet.Range("Table1[[#Headers],[Series 1]]").FormulaR1C1 = vRigName & " Non-Conformance Distribution"
rs.Open ssql, CurrentProject.Connection, adOpenStatic, adLockReadOnly
If Not rs.EOF Then
i = 2
Do While Not rs.EOF()
chartWorkSheet.Range("A" & i).FormulaR1C1 = rs.Fields("checklistdesc")
chartWorkSheet.Range("B" & i).FormulaR1C1 = rs.Fields("nccount")
i = i + 1
rs.MoveNext
Loop
End If
rs.Close
chartWorkSheet.ListObjects("Table1").Resize chartWorkSheet.Range("A1:B" & i - 1)
' Configure chart to show the values
With objChart
With .SeriesCollection(1)
.HasDataLabels = True
.DataLabels.ShowValue = True
.HasLeaderLines = True
.DataLabels.ShowCategoryName = True
End With
End With
' set the fonts
Debug.Print " Setting the fonts of the labels ..1."
objChart.ChartArea.Font.Size = 9
objChart.ChartArea.Font.Name = gsFontForzaMedium
' Set the location of the chart
With objChart.Parent
.Height = 450
.Top = 60
End With
' show the document
mobjWordApp.visible = True
' Close the spreadsheet chart object
objChart.ChartData.Workbook.Application.Quit
' Clear the objects
Set rs = Nothing
Set clsRig_ = Nothing
Set clsAudit_ = Nothing
' Set function to status OK
gbAuditReportGraphs = True
ex:
Exit Function
eh:
gError "Problem creating audit report graphs", "modADCForms", "gbAuditReportGraphs", Err, Error
Resume ex
End Function
Cindy, I have taken your value advice, and fixed it :)
Pass in parameter of the range
Public Function gbAuditReportGraphs(ByVal lAuditID As Long, rng As Range) As Boolean
Create chart as an inline shape
Set objChart = mobjWordDoc.InlineShapes.AddChart.Chart
objChart.ChartType = xlPie
Set the size with code such as
With mobjWordApp.ActiveDocument
.InlineShapes(1).Height = 450
.InlineShapes(1).Width = 400
End With
Copy and paste chart into the specified range
objChart.Copy
rng.Paste
Delete the original
objChart.Delete
I could find no other advice on how to do this; perhaps this post will help others.
One tip to make your solution more robust: Generally, you can't be sure that the InlineShape you insert is the first in the document, so ActiveDocument.InlineShapes(1) isn't reliable. Better to declare an InlineShape object and assign the InlineShape belonging to the chart to it, so you can be sure you're working with the right InlineShape:
'1.Pass in parameter of the range
Public Function gbAuditReportGraphs(ByVal lAuditID As Long, _
rng As Range) As Boolean
Dim objChart as Word.Chart
Dim objInlineShape as Word.InlineShape
'2.Create chart as an inline shape
Set objChart = mobjWordDoc.InlineShapes.AddChart.Chart
objChart.ChartType = xlPie
'3.Set the size with code such as
Set objInlineShape = objChart.Parent
With objInlineShape
.Height = 450
.Width = 400
End With
'4.Copy and paste chart into the specified range
objChart.Copy
rng.Paste
'5.Delete the original
objChart.Delete
End Function
I have small Template for MS Word. I want to add comment with hyperlink. I can already add the comment with the following code, but I want to set the author name of that comment. I don't know how to do that.
Here is my working code: (author is not set currently)
URLText = "https:\\www.google.com"
Selection.Comments.Add Range:=Selection.Range
With Selection
.TypeText (CommentText) 'Add comment text
.Hyperlinks.Add Anchor:=Selection.Range, _ 'Add hyperlink to comment
Address:=URLText, _
ScreenTip:=URLText, _
TextToDisplay:=URLText
End With
However I have tried by following code. Which set author name but I can't add hyperlink in my comment by this way:
Dim cmtMyComment As Comment
Dim link As Hyperlink
link.Address = URLText
link.ScreenTip = URLText
link.TextToDisplay = URLText
Set cmtMyComment = Selection.Comments.Add(Range:=Selection.Range, _
Text:=(CommentText)
cmtMyComment.Author = "ABC"
I didn't find property to set hyperlink.
Can anybody suggest me how to set author name? I have tried but didn't find any property.
Well there is an Author property which you can set like so and the hyperlink still works as you can see with the GIF below
Public Sub AddCommentWithLink()
URLText = "https:\\www.google.com"
Set Comment = Selection.Comments.Add(Range:=Selection.Range)
Comment.Author = "Donald Duck"
With Selection
.TypeText (CommentText)
.Hyperlinks.Add Anchor:=Selection.Range, _
Address:=URLText, _
ScreenTip:=URLText, _
TextToDisplay:=URLText
End With
End Sub
Which will result in a comment like this
I want to use Excel VBA to set up Task Reminders in Outlook, so I found this code from here:
http://www.jpsoftwaretech.com/using-excel-vba-to-set-up-task-reminders-in-outlook/
Dim bWeStartedOutlook As Boolean
Function AddToTasks(strDate As String, strText As String, DaysOut As Integer) As Boolean
=AddToTasks(B2, M2 Time, 120)
' Adds a task reminder to Outlook Tasks a specific number of days before the date specified
' Returns TRUE if successful
' Will not trigger OMG because no protected properties are accessed
' by Jimmy Pena, http://www.jpsoftwaretech.com, 10/30/2008
'
' Usage:
' =AddToTasks("12/31/2008", "Something to remember", 30)
' or:
' =AddToTasks(A1, A2, A3)
' where A1 contains valid date, A2 contains task information, A3 contains number of days before A1 date to trigger task reminder
'
' can also be used in VBA :
'If AddToTasks("12/31/2008", "Christmas shopping", 30) Then
' MsgBox "ok!"
'End If
Dim intDaysBack As Integer
Dim dteDate As Date
Dim olApp As Object ' Outlook.Application
Dim objTask As Object ' Outlook.TaskItem
' make sure all fields were filled in
If (Not IsDate(strDate)) Or (strText = "") Or (DaysOut <= 0) Then
AddToTasks = False
GoTo ExitProc
End If
' We want the task reminder a certain number of days BEFORE the due date
' ex: if DaysOut = 120, then we want the due date to be -120 before the date specified
' we need to pass -120 to the NextBusinessDay function, so to go from 120 to -120,
' we subtract double the number (240) from the number provided (120).
' 120 - (120 * 2); 120 - 240 = -120
intDaysBack = DaysOut - (DaysOut * 2)
dteDate = NextBusinessDay(CDate(strDate), intDaysBack)
On Error Resume Next
Set olApp = GetOutlookApp
On Error GoTo 0
If Not olApp Is Nothing Then
Set objTask = olApp.CreateItem(3) ' task item
With objTask
.StartDate = dteDate
.Subject = strText & ", due on: " & strDate
.ReminderSet = True
.Save
End With
Else
AddToTasks = False
GoTo ExitProc
End If
' if we got this far, it must have worked
AddToTasks = True
ExitProc:
If bWeStartedOutlook Then
olApp.Quit
End If
Set olApp = Nothing
Set objTask = Nothing
End Function
Function GetOutlookApp() As Object
On Error Resume Next
Set GetOutlookApp = GetObject(, "Outlook.Application")
If Err.Number <> 0 Then
Set GetOutlookApp = CreateObject("Outlook.Application")
bWeStartedOutlook = True
End If
On Error GoTo 0
End Function
Sub Test()
My question is, if I have all the data in the spreadsheet, and I initiallize AddToTasks like so:
=AddToTasks(A1, A2, 120)
Why does it come up with that error?
You need to call AddToTasks from a separate Subroutine. (Right now you are trying to call it from inside itself.) So, create a separate Subroutine something like this:
Sub CallAddToTasksFunction
If AddToTasks("12/31/2008", "Something to remember", 30) = True Then
Debug.Print "Task Added"
Else
Debug.Print "Failed"
End If
End Sub
AddToTasks returns True or False depending on if it succeeded. You can see where that happens in a couple of spots in the function where the code is like:
AddToTasks = False (or True)
and you can see that things like dates that aren't really dates will cause it to fail.
I have a user form in Word 2007 which searches for specific terms in a document and adds comments. I have three different categories for these comments. I want the comments to be color coded for each category. For the moment I have a solution which works but it is very slow. Is there another way to assign a comment author directly when creating the comments?
Code for comment creation:
For i = 0 To UBound(CritArray)
PosCount = 1
With Selection
.HomeKey wdStory
With .Find
.ClearFormatting
Do While .Execute(FindText:=CritArray(i), _
Forward:=True, _
MatchWholeWord:=True)
Select Case i
...
End Select
PosCount = PosCount + 1
Selection.Comments.Add _
Range:=Selection.Range, _
Text:=MessArray(i) & CritArray(i) & "' - found for the" & Str(FoundCount) & ". time"
Loop
End With
End With
Next
Code for assigning a different author to each comment - this results in different color coded comments if under Review>Track Changes>Track Changes Options>Comments by author is selected:
Dim CurrentExpField As String
For Each objCom In ActiveDocument.Comments
CurrentExpField = Left$(objCom.Range.Text, 3)
objCom.Author = UCase(CurrentExpField)
objCom.Initial = UCase(CurrentExpField)
Next
Yes, it is possible to set additional properties for a Comment after it is created since the Add method for Comments returns a reference to a new Comment object. This means that you can do your colour-coding in one pass. I modified your code slightly to do this as follows:
Dim cmtMyComment as Comment
For i = 0 To UBound(CritArray)
PosCount = 1
With Selection
.HomeKey wdStory
With .Find
.ClearFormatting
Do While .Execute(FindText:=CritArray(i), _
Forward:=True, _
MatchWholeWord:=True)
Select Case i
...
End Select
PosCount = PosCount + 1
Set cmtMyComment = Selection.Comments.Add(Range:=Selection.Range, _
Text:=MessArray(i) & CritArray(i) & "' - found for the" & Str(FoundCount) & ". time")
cmtMyComment.Author = UCase(Left$(cmtMyComment.Range.Text, 3))
cmtMyComment.Initial = UCase(Left$(cmtMyComment.Range.Text, 3))
Loop
End With
End With
Next