none
Using Visual Studio VB.net to modify Multilpe word documents RRS feed

  • Question

  • I want to write code that will open folders and find all the word documents one file at a time and modify the headers/footers, search for a string such as <company Name> and replace it with another string, etc

     

    Does anyone know of any good visual studio prgramming manuals for MS Word 2010 that covers topics like this

    Friday, September 20, 2013 9:57 PM

Answers

  • Hi,

    According to your description, you want to modify the headers/footers and replace some special strings in the Word documents of a folder.

    I write a sample to loop all of the word files of a folder ("C:\Users\Documents\testWord") and then modify them as you want for your reference.

    Sub OpenWordFileModify()
    Dim objWord As Object = New Microsoft.Office.Interop.Word.Application()
    Dim FileName As String
    Dim selectedDir As String
    
    selectedDir = "C:\Users\Documents\testWord"
    FileName = Dir(selectedDir & "\*.docx")
    
    Do While FileName <> ""
    
        ModifyWord(selectedDir & "\" & FileName)
    
        FileName = Dir()
    Loop
    
    objWord.Quit()
    End Sub
    
    Sub ModifyWord(wdFileName As Object)
    Dim wdDoc As Object
    
    If wdFileName = "" Then Exit Sub 
    
    wdDoc = GetObject(wdFileName) 'open Word file
    With wdDoc
        With .Sections(1)
            .Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Text = "Header text"
            .Footers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Text = "Footer text"
        End With
    
        With .Content.Find
            .ClearFormatting()
            .Text = "<company Name>"
            .Replacement.ClearFormatting()
            .Replacement.Text = "TEST"
            .Execute(Replace:=Word.WdReplace.wdReplaceAll, Forward:=True, _
                Wrap:=Word.WdFindWrap.wdFindContinue)
        End With
    
        .Save()
    End With
    wdDoc.Close()
    wdDoc = Nothing
    End Sub
    


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Tuesday, September 24, 2013 6:00 AM
    Moderator