Search code examples
c#excellinked-listms-wordpassword-protection

update password protected linked word document in C#


Let me first describe the problem. I have this application that opens a word document and updates all the fields and then saves the document in another folder. The word document is just used as a template for a report. It is filled with linked content from an excel worksheet. The whole application works, but the problem is that the excel document is password protected. when I update the document fields the application is stopped and word asks for a password.

When you input the password, the program works as advertised, you have to insert it more than once thou, dont really know why. But the program is suppose to work autonomously without user input. Is there a way to give word the password so that it doesnt have to be entered, either via code or in the word document properties.

Below is my current code that does this, its in C#

    Microsoft.Office.Interop.Word.Application ap = new Microsoft.Office.Interop.Word.Application();
        Document doc = ap.Documents.Open(template, ReadOnly: false, Visible: false);
        doc.Activate();
        red_debug.AppendText("opening " + template + "\n");
        doc.Fields.UpdateSource();
        doc.Fields.Update();
        red_debug.AppendText("Saving as " + final + "\n");
        doc.SaveAs(final, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument);
        doc.SaveAs(path + "\\" + name, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF);
        red_debug.AppendText("Closing word" + "\n");
        doc.Close();
        ap.Quit();

Solution

  • Get the Word document to open up the Excel file (with the password) for you everytime it has been opened. Same time, we can also successfully close the Excel file from Word.

    Put this into the Word macro area.

    Private Sub Document_Open()
    
    Dim xlApp As Object
    Dim xlWB As Object
    Dim myRange
    
    Application.DisplayAlerts = wdAlertsNone
    
    Set xlApp = CreateObject("Excel.Application")
    Set xlWB = xlApp.Workbooks.Open("C:\ExcelFile.xls", , , , "password", "password")
    Set myRange = Selection.Range
    
        Selection.WholeStory
        Selection.Fields.Update
        myRange.Select
    
    xlApp.Quit
    Set xlWB = Nothing
    Set xlApp = Nothing
    
    Application.DisplayAlerts = wdAlertsAll
    
    End Sub
    

    This will open up the excel document and update ALL fields on your word document and shouldnt ask you for password