web-dev-qa-db-fra.com

Macro pour exporter des tableaux MS Word vers des feuilles Excel

J'ai un document Word avec de nombreux tableaux. Quelqu'un sait-il comment écrire une macro pour exporter de tels tableaux vers différentes feuilles Excel?

24
QLands

Réponse tirée de: http://www.mrexcel.com/forum/showthread.php?t=36875

Voici un code qui lit un tableau de Word dans la feuille de calcul active d'Excel. Il vous invite à saisir le document Word ainsi que le numéro du tableau si Word contient plusieurs tableaux.

Sub ImportWordTable()
Dim wdDoc As Object
Dim wdFileName As Variant
Dim TableNo As Integer 'table number in Word
Dim iRow As Long 'row index in Excel
Dim iCol As Integer 'column index in Excel

wdFileName = Application.GetOpenFilename("Word files (*.doc),*.doc", , _
"Browse for file containing table to be imported")

If wdFileName = False Then Exit Sub '(user cancelled import file browser)

Set wdDoc = GetObject(wdFileName) 'open Word file

With wdDoc
    TableNo = wdDoc.tables.Count
    If TableNo = 0 Then
        MsgBox "This document contains no tables", _
        vbExclamation, "Import Word Table"
    ElseIf TableNo > 1 Then
        TableNo = InputBox("This Word document contains " & TableNo & " tables." & vbCrLf & _
        "Enter table number of table to import", "Import Word Table", "1")
    End If
    With .tables(TableNo)
        'copy cell contents from Word table cells to Excel cells
        For iRow = 1 To .Rows.Count
            For iCol = 1 To .Columns.Count
                Cells(iRow, iCol) = WorksheetFunction.Clean(.cell(iRow, iCol).Range.Text)
            Next iCol
        Next iRow
    End With
End With

Set wdDoc = Nothing

End Sub

Cette macro doit être insérée dans Excel (pas Word) et placée dans un module de macro standard plutôt que dans les modules de code d'événement de feuille de calcul ou de classeur. Pour ce faire, accédez au VBA (clavier Alt-TMV), insérez un module macro (Alt-IM) et collez le code dans le volet de code. Exécutez la macro à partir de l'interface Excel comme vous le feriez pour n'importe quelle autre (Alt-TMM).

Si votre document contient de nombreux tableaux, comme ce serait le cas si votre tableau de 100+ pages est en fait un tableau distinct sur chaque page, ce code pourrait facilement être modifié pour lire tous les tableaux. Mais pour l'instant, j'espère que ce n'est qu'une table continue et ne nécessitera aucune modification.


Continuez d'exceller.

Damon

VBAexpert Excel Consulting (Mon autre vie: http://damonostrander.com )

29
Bnjmn

J'ai changé celui-ci avec un ajout pour parcourir toutes les tables (à partir de la table choisie):

Option Explicit

Sub ImportWordTable()

Dim wdDoc As Object
Dim wdFileName As Variant
Dim tableNo As Integer 'table number in Word
Dim iRow As Long 'row index in Excel
Dim iCol As Integer 'column index in Excel
Dim resultRow As Long
Dim tableStart As Integer
Dim tableTot As Integer

On Error Resume Next

ActiveSheet.Range("A:AZ").ClearContents

wdFileName = Application.GetOpenFilename("Word files (*.doc),*.doc", , _
"Browse for file containing table to be imported")

If wdFileName = False Then Exit Sub '(user cancelled import file browser)

Set wdDoc = GetObject(wdFileName) 'open Word file

With wdDoc
    tableNo = wdDoc.tables.Count
    tableTot = wdDoc.tables.Count
    If tableNo = 0 Then
        MsgBox "This document contains no tables", _
        vbExclamation, "Import Word Table"
    ElseIf tableNo > 1 Then
        tableNo = InputBox("This Word document contains " & tableNo & " tables." & vbCrLf & _
        "Enter the table to start from", "Import Word Table", "1")
    End If

    resultRow = 4

    For tableStart = 1 To tableTot
        With .tables(tableStart)
            'copy cell contents from Word table cells to Excel cells
            For iRow = 1 To .Rows.Count
                For iCol = 1 To .Columns.Count
                    Cells(resultRow, iCol) = WorksheetFunction.Clean(.cell(iRow, iCol).Range.Text)
                Next iCol
                resultRow = resultRow + 1
            Next iRow
        End With
        resultRow = resultRow + 1
    Next tableStart
End With

End Sub

Astuce suivante: trouver comment extraire une table dans une table de Word ... et est-ce que je veux vraiment?

TC

18
Tim

Cette section de code est celle qui parcourt chaque table et la copie dans Excel. Vous pouvez peut-être créer un objet de feuille de calcul qui met à jour dynamiquement la feuille de calcul à laquelle vous faites référence en utilisant le numéro de table comme compteur.

With .tables(TableNo)
'copy cell contents from Word table cells to Excel cells
For iRow = 1 To .Rows.Count
For iCol = 1 To .Columns.Count
Cells(iRow, iCol) = WorksheetFunction.Clean(.cell(iRow, iCol).Range.Text)
Next iCol
Next iRow
End With
End With
0
Bnjmn

Merci beaucoup Damon et @Tim

Je l'ai modifié pour ouvrir des fichiers docx, déplacé une ligne claire de feuille de calcul après avoir vérifié l'échappement par l'utilisateur.

Voici le code final:

Option Explicit

Sub ImportWordTable()

Dim wdDoc As Object
Dim wdFileName As Variant
Dim tableNo As Integer      'table number in Word
Dim iRow As Long            'row index in Excel
Dim iCol As Integer         'column index in Excel
Dim resultRow As Long
Dim tableStart As Integer
Dim tableTot As Integer

On Error Resume Next

wdFileName = Application.GetOpenFilename("Word files (*.docx),*.docx", , _
"Browse for file containing table to be imported")

If wdFileName = False Then Exit Sub '(user cancelled import file browser)

ActiveSheet.Range("A:AZ").ClearContents

Set wdDoc = GetObject(wdFileName) 'open Word file

With wdDoc
    tableNo = wdDoc.tables.Count
    tableTot = wdDoc.tables.Count
    If tableNo = 0 Then
        MsgBox "This document contains no tables", _
        vbExclamation, "Import Word Table"
    ElseIf tableNo > 1 Then
        tableNo = InputBox("This Word document contains " & tableNo & " tables." & vbCrLf & _
        "Enter the table to start from", "Import Word Table", "1")
    End If

    resultRow = 4

    For tableStart = tableNo To tableTot
        With .tables(tableStart)
            'copy cell contents from Word table cells to Excel cells
            For iRow = 1 To .Rows.Count
                For iCol = 1 To .Columns.Count
                    Cells(resultRow, iCol) = WorksheetFunction.Clean(.cell(iRow, iCol).Range.Text)
                Next iCol
                resultRow = resultRow + 1
            Next iRow
        End With
        resultRow = resultRow + 1
    Next tableStart
End With

End Sub
0
Sujay Phadke