Batch File Formatting with Visual Basic

Below is an example of how paragraphs of text in Microsoft Word documents can be formatted in a batch, based on specified paragraph text.

Firstly, the file path is set, together with a list of paragraphs containing particular text to format. A check is then made to see if the file path exists and whether there are any files to format. Each file is then processed one by one. All files without a ‘.docx’ extension are ignored. For each paragraph of text within a document, a check is made to see if its text matches any item in the paragraphs to format list. If a match is found the text is formatted.

Feedback is given as to the number of paragraphs that have been formatted in each file, along with a total count of files formatted at the end.

Imports System.IO
Imports Microsoft.Office.Interop

Public Class BatchFileFormatting

    Public Shared Sub Main()

        ' File path.
        Dim filePath As String = "C:\Demo"

        ' List of paragraphs to format.
        Dim parasToFormat As New List(Of String)(New String() {
            "Example Heading 1",
            "Example Heading 2",
            "Example Heading 3"
        })

        ' File extension.
        Dim fileExtension As String

        ' Check if the file path exists.
        If Directory.Exists(filePath) Then

            ' Return the names of the files at the specified path.
            Dim dirFiles As String() = Directory.GetFiles(filePath)

            ' Check if there are any files at the path.
            If dirFiles.Length = 0 Then

                ' Message stating there are no files to format.
                Console.WriteLine("There are no files to format.")

            Else

                ' Microsoft Word file variables.
                Dim wdApp As New Word.Application()
                Dim wdDocument As Word.Document

                ' Formatted file and paragraph counts.
                Dim filesFormatted As Integer = 0
                Dim paragraphsFormatted As Integer = 0

                ' Process the files at the path.
                For Each dirFile As String In dirFiles

                    ' Extract the file extension from the name.
                    fileExtension = Path.GetExtension(dirFile)

                    ' Check if the file is a Word file.
                    If fileExtension = ".docx" And Not dirFile.Contains("~") Then

                        Try

                            ' Open the Word document.
                            wdDocument = wdApp.Documents.Open(dirFile)

                            ' Process the paragraphs in the document.
                            For Each para As Word.Paragraph In wdDocument.Paragraphs

                                ' Check if the paragraph text is one that needs formatting.
                                If parasToFormat.Contains(para.Range.Text.ToString().Trim()) Then

                                    ' Format the paragraph font, weight and size.
                                    para.Range.Font.Name = "Arial"
                                    para.Range.Font.Bold = -1
                                    para.Range.Font.Size = 14

                                    ' Indicate a paragraph has been formatted.
                                    paragraphsFormatted += 1

                                End If

                            Next

                            ' Check if any paragraphs have been formatted.
                            If paragraphsFormatted > 0 Then

                                ' Increment the files formatted count.
                                filesFormatted += 1

                                ' Save the document.
                                wdDocument.Save()

                                ' Message displaying file formatting information.
                                If paragraphsFormatted = 1 Then

                                    Console.WriteLine("{0} paragraph formatted in the file " +
                                        """{1}"".", paragraphsFormatted, dirFile.ToString())

                                Else

                                    Console.WriteLine("{0} paragraphs formatted in the file" +
                                        " ""{1}"".", paragraphsFormatted, dirFile.ToString())

                                End If

                                ' Reset the paragraphs formatted variable.
                                paragraphsFormatted = 0

                            Else

                                ' Message stating no paragraphs formatted in the file.
                                Console.WriteLine("No paragraphs formatted in the file" +
                                    " ""{0}"".", dirFile.ToString())

                            End If

                            ' Close the Word document.
                            wdDocument.Close()

                        Catch ex As Exception

                            ' Message confirming the file could not be formatted.
                            Console.WriteLine("The file ""{0}"" could not be formatted.",
                                    dirFile.ToString())

                        End Try

                    End If

                Next

                ' Message stating the number of files formatted.
                If filesFormatted = 0 Then

                    Console.WriteLine("No files have been formatted.")

                ElseIf filesFormatted = 1 Then

                    Console.WriteLine("{0} file has been formatted.", filesFormatted)

                Else

                    Console.WriteLine("{0} files have been formatted.", filesFormatted)

                End If

                ' Close Microsoft Word.
                wdApp.Quit()

            End If

        Else

            ' Display a message stating file path does not exist.
            Console.WriteLine("File path does not exist.")

        End If

        ' Force console window to stay open until a key is pressed.
        Console.ReadKey()

    End Sub

End Class