I want to copy/paste tables from an Excel sheet toward a .docx. I have a word #tableauxvdd which I want to replace by my tables.
So I wrote this code
With word_fichier.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "#tableauxvdd"
.Replacement.Text = "#tableauxvdd"
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = True
.Execute Replace:=wdReplaceNone
End With
If .Find.Found = True Then
For i = 1 To nombre_de_vdd
Set tblRangeVdd = ThisWorkbook.Worksheets("Info vdd " & i).Range("A1:C6")
tblRangeVdd.Copy
.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False
Next
End If
End With
But its not working. Here is the tables I need to copy/paste
CodePudding user response:
Whenever you write code to automate Word you need to think through what steps you would take if you were performing the task in the UI.
In a Word document, tables are always separated by a paragraph, so your code needs to do the same.
For example:
If .Find.Found = True Then
For i = 1 To nombre_de_vdd
Set tblRangeVdd = ThisWorkbook.Worksheets("Info vdd " & i).Range("A1:C6")
tblRangeVdd.Copy
.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False
.InsertParagraphAfter
Next
End If
You'll also need to add the tables in reverse order, for example:
If .Find.Found = True Then
Dim tblRangeVdd As word.Range
Set tblRangeVdd = .Duplicate
With tblRangeVdd
.Collapse wdCollapseEnd
For i = nombre_de_vdd To 1 Step -1
ThisWorkbook.Worksheets("Info vdd " & i).Range("A1:C6").Copy
.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False
.InsertParagraphAfter
Next
End With
End If