Based on some of the logic and objects in this excel standalone subroutine, please write a Word VBA function which runs on the active document to list the margins in a comma-delimited list for every section with greater than 1 page of length:
Sub FindMargins()
code
Dim wordApp As Word.Application
Set wordApp = New Word.Application
Dim resultsSheet As Worksheet
Set resultsSheet = ActiveSheet
Dim curCell As Range
Set curCell = resultsSheet.Range("A3")
Dim intResult As Long
Dim docCur As Document
Dim intSecNum As Integer
Dim curSecPage As Integer
Dim prevSecPage As Integer
Dim dblStartTime As Double
Dim vDirectory As String
Dim prodName As String
' Asks the user which file to run in
Application.FileDialog(msoFileDialogFolderPicker).InitialFileName = "C:"
intResult = Application.FileDialog(msoFileDialogFolderPicker).Show
If intResult <> 0 Then
vDirectory = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1)
Else
MsgBox ("There was an issue with the selection. Please try again.")
Exit Sub
End If
prodName = Dir(vDirectory & "\" & "*.doc*")
' Cycles through each document in the selected folder
Do While prodName <> ""
Set docCur = wordApp.Documents.Open(Filename:=vDirectory & "\" & prodName, Visible:=False, ReadOnly:=True, AddToRecentFiles:=False)
wordApp.ScreenUpdating = False
dblStartTime = Timer
' --- First Row: Margins ---
curCell.Value = prodName
curCell.Offset(0, 2).Value = "Margins (Left & Right)"
' Loop through sections to write margin data starting in Column C
For intSecNum = 1 To docCur.Sections.Count
On Error Resume Next
curCell.Offset(0, 2 + intSecNum).Value = docCur.Sections(intSecNum).PageSetup.LeftMargin & " & " & docCur.Sections(intSecNum).PageSetup.RightMargin
On Error GoTo 0
Next intSecNum
' --- Second Row: Page Counts ---
Set curCell = curCell.Offset(1, 0) ' Move to the next row for the second set of data
curCell.Value = prodName
curCell.Offset(0, 2).Value = "Page Counts"
prevSecPage = 0
For intSecNum = 1 To docCur.Sections.Count
On Error Resume Next
curSecPage = docCur.Sections(intSecNum).Range.Information(wdActiveEndPageNumber)
curCell.Offset(0, 2 + intSecNum).Value = curSecPage - prevSecPage
prevSecPage = curSecPage
On Error GoTo 0
Next intSecNum
' Write the elapsed time in Column B for both rows
Dim elapsedTime As Double
elapsedTime = Round(Timer - dblStartTime, 2)
curCell.Offset(-1, 1).Value = elapsedTime ' Time for margin row
curCell.Offset(0, 1).Value = elapsedTime ' Time for page count row
docCur.Close SaveChanges:=wdDoNotSaveChanges
' Move to the next available row for the next document
Set curCell = curCell.Offset(1, 0)
prodName = Dir
Loop
wordApp.Quit
Set wordApp = Nothing ' release the memory
MsgBox ("Done")
End Sub
Assistant
Below is a Word VBA function that runs on the active document to list the margins (left and right) in a comma-delimited list for every section with more than 1 page of length. This function is adapted from the logic in your Excel VBA subroutine but is tailored to work within Word VBA and focus on the active document.
Key Adaptations:
Context: The function operates on the active document in Word, so there's no need to open files or loop through a directory.
Output: Instead of writing to an Excel worksheet, the function returns a comma-delimited string of margins for qualifying sections.
Section Filtering: Only sections with more than 1 page are included, as per your requirement.
Error Handling: Basic error handling is included to manage potential issues with section access or page counts.
Word VBA Function:
vba
Function GetMarginsForMultiPageSections() As String
' This function returns a comma-delimited list of margins (Left & Right)
' for sections in the active document that have more than 1 page.
Dim doc As Document
Dim sec As Section
Dim intSecNum As Integer
Dim curSecPage As Integer
Dim prevSecPage As Integer
Dim marginList As String
Dim pageCount As Integer
' Initialize variables
Set doc = ActiveDocument
marginList = ""
prevSecPage = 0
' Loop through each section in the active document
For intSecNum = 1 To doc.Sections.Count
On Error Resume Next ' Handle potential errors with section access
' Get the page count for the current section
curSecPage = doc.Sections(intSecNum).Range.Information(wdActiveEndPageNumber)
pageCount = curSecPage - prevSecPage
' If the section has more than 1 page, include its margins
If pageCount > 1 Then
' Append margins to the list in the format "Left & Right"
If marginList <> "" Then
marginList = marginList & ", "
End If
marginList = marginList & doc.Sections(intSecNum).PageSetup.LeftMargin & " & " & doc.Sections(intSecNum).PageSetup.RightMargin
End If
' Update the previous section's page number
prevSecPage = curSecPage
On Error GoTo 0 ' Reset error handling
Next intSecNum
' Return the comma-delimited list of margins
If marginList = "" Then
GetMarginsForMultiPageSections = "No sections with more than 1 page found."
Else
GetMarginsForMultiPageSections = marginList
End If
End Function
To use this function, you can call it from another VBA procedure in Word and display or use the result. Here's an example of how to test it:
vba
Sub TestGetMargins()
Dim result As String
result = GetMarginsForMultiPageSections()
MsgBox "Margins for sections with more than 1 page: " & vbCrLf & result
End Sub
Explanation of the Code:
Variables:
doc: References the active Word document.
sec: Represents a section in the document (used in the loop).
intSecNum: Tracks the current section number.
curSecPage and prevSecPage: Used to calculate the page count of each section.
marginList: Stores the comma-delimited list of margins.
pageCount: Stores the number of pages in the current section.
Page Count Calculation:
The page count for each section is determined by subtracting the ending page number of the previous section (prevSecPage) from the ending page number of the current section (curSecPage).
This is done using the Range.Information(wdActiveEndPageNumber) property, which returns the page number of the last page in the section.
Margin Inclusion:
If a section has more than 1 page (pageCount > 1), its left and right margins are appended to marginList in the format "Left & Right".
Margins are separated by commas for sections that qualify.
Error Handling:
On Error Resume Next is used to handle potential errors when accessing section properties, such as if a section is corrupt or inaccessible.
On Error GoTo 0 resets error handling after each section is processed.
Output:
If no sections with more than 1 page are found, the function returns a message indicating this.
Otherwise, it returns the comma-delimited list of margins.
Notes:
Units: The margins are returned in points (Word's default unit for margins). If you need them in another unit (e.g., inches), you can convert them by dividing by 72 (since 1 inch = 72 points).
Active Document: This function assumes there is an active document open in Word. If no document is open, you will need to add error handling or open a document programmatically.
Performance: For very large documents, performance could be improved by minimizing screen updates (e.g., Application.ScreenUpdating = False), though this is less critical in Word VBA compared to Excel VBA.
This function provides a streamlined way to extract margin information from the active document, focusing on sections with multiple pages, as requested.