'Modify a word document with excel

i've tried do create a code which is able to modify a text from a word document. I can't find the mistake and everytime i run it, there is a new error. Here what i've tried. Can you help me, please?

Option Explicit
Dim Wordapp As Object
Dim worddoc As Object



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 'traite le texte contenu dans excel


worddoc.Close SaveChanges:=True

Wordapp.Quit



End Sub

Private Sub traitement_champs()
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 contenu 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.Text = ws.Cells(i, 4).Value
    Next ctrl
    
Next i



End Sub


Solution 1:[1]

The global objects (the two lines after Option Explicit) are not the same objects declares in export_Automatisation_MT().

When you call traitement_champs(), it refers to worddoc, which will be the unassigned global variable.

To fix, remove the global Dim's and add a parameter to traitement_champs()

Sub traitement_champs(worddoc as Word.Document)

Update the call to (no need for the Call keyword)

traitement_champs worddoc

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1