Generate a word document with excel

Viewed 98

I've modificated the code following the last advices that I've recived. However I still can't generate the new word document using my VBA code from Excel.

I would like that Excel will able to modificate text content and generate a new document that it will open when I click on the button.

Here what I've done enter image description here

And this is the code and it says I have a "91 error" for the line worddoc.Close SaveChanges:=False

there the code:

Sub export_Automatisation_MT() 'nom du maccro
    Dim wordapp As Word.Application
    Dim worddoc As Word.Document

    Set wordapp = CreateObject("word.application") 'crée une application word
    Set worddoc = wordapp.Documents.Open("O:\Projets\RAZAN BORKI\01 MEMOIRE TECHNIQUE.docx") 'document de base

    Call traitement_champs(worddoc) 'traite le texte contenu dans excel

    worddoc.Close SaveChanges:=False
    wordapp.Quit
End Sub


Private Sub traitement_champs(worddoc As Word.Document)
    Dim ws As Worksheet
    Dim derLigne As Integer
    Dim i As Integer
    Dim ctrl As Object 'control du contenu

    Set ws = Sheets("Mémoire technique")

    derLigne = ws.Range("C" & Rows.Count).End(xlUp).Row

    For i = 3 To derLigne
        On Error Resume Next 'si erreur, pas de contrôle de contnu de texte dans word
        
        Debug.Print "champ:" & ws.Cells(i, 3).Value & "valeur:" & ws.Cells(i, 4).Value
        
        For Each ctrl In worddoc.SelectContentControlsByTitle(ws.Cells(i, 3).Value)
            ctrl.Range.Value = ws.Cells(i, 4).Value
        Next ctrl
    Next i
End Sub
1 Answers

First of all: you should remove the on error resume next!

You don't use call and brackets to call a sub. Simply use traitement_champs worddoc

Make following changes to the sub: Dim ctrl as Word.ContentControl instead of as Object

ctrl.Range.Text = ws.cells(i,4)).value (Word ranges only have the text attribute - no value (like Excel))

worddoc.Close SaveChanges:=False looks ok - except it doesn't make sense to me, to open and edit the doc and then close it without saving.

Related