Vba чтение таблицы word

0 / 0 / 0

Регистрация: 09.05.2012

Сообщений: 52

1

26.12.2012, 20:29. Показов 7829. Ответов 3


Студворк — интернет-сервис помощи студентам

Имеется файл Word. В этом файле имеется таблица(4 на 3). Нужно перенести эти данные в Excel и решить матрицу(матрицу уже решать с помощью функций EXCEL, а не на VBA).

Помогите пожалуйста! Вся сложность состоит в том, чтобы «выдрать» данные из таблицы Word с помощью VBA.

Миниатюры

Как получить данные из таблицы Word
 



0



15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

26.12.2012, 21:05

2



1



0 / 0 / 0

Регистрация: 09.05.2012

Сообщений: 52

26.12.2012, 21:41

 [ТС]

3

не совсем понятно, пытался делать как там написано, но в эксел вставляется массив в виде картинки, а мне нужно чтобы ячейки заполнялись числами



0



Catstail

Модератор

Эксперт функциональных языков программированияЭксперт Python

34706 / 19227 / 4039

Регистрация: 12.02.2012

Сообщений: 32,183

Записей в блоге: 13

27.12.2012, 13:24

4

Лучший ответ Сообщение было отмечено как решение

Решение

Цитата
Сообщение от Drop8Dead
Посмотреть сообщение

решить матрицу

— решают уравнения…

А получить массив из таблицы Worda (при условии, что документ содержит единственную таблицу) можно так:

Visual Basic
1
2
3
4
5
6
7
8
9
Sub GetMatr(A() as double, wdDoc As Word.Document)
Dim tbl as Word.Table
      Set tbl=wdDoc.tables(1) ' если таблиц несколько - можно задать другой номер
      For i%=1 to 3
           For j%=1 to 4
                A(i%,j%)=Val(tbl.Cell(i%,j%).Range.Text)
           Next j%
      Next i%
End Sub

У проекта должна быть установлена ссылка на объектную библиотеку Worda.



3



Need help to modify this VBA code to read multiple tables from a Word document. It only reads one table, but I would like to import more than one into the same Excel sheet.

Sub ImportWordTables()
   'Imports a table from Word document 

   Dim wdDoc         As Object
   Dim wdFileName    As Variant
   Dim TableNo       As Integer  'number of tables in Word doc
   Dim iTable        As Integer  'table number index
   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

Community's user avatar

asked Jul 27, 2014 at 23:40

user601828's user avatar

So this is the code, but it doesn’t entirely answer my questions.
I just need the tables from the pdf.

Sub Imp_Into_XL(PDF_File As String, Each_Sheet As Boolean)

'This procedure get the PDF data into excel by following way

'1.Open PDF file
'2.Looping through pages
'3.get the each PDF page data into individual _
  sheets or single sheet as defined in Each_Sheet Parameter


Dim AC_PD As Acrobat.AcroPDDoc              'access pdf file
Dim AC_Hi As Acrobat.AcroHiliteList         'set selection word count
Dim AC_PG As Acrobat.AcroPDPage             'get the particular page
Dim AC_PGTxt As Acrobat.AcroPDTextSelect    'get the text of selection area

Dim WS_PDF As Worksheet
Dim RW_Ct As Long                           'row count
Dim Col_Num As Integer                      'column count
Dim Li_Row As Long                          'Maximum rows limit for one column
Dim Yes_Fir As Boolean                      'to identify beginning of page

Li_Row = Rows.Count

Dim Ct_Page As Long                         'count pages in pdf file
Dim i As Long, j As Long, k As Long         'looping variables
Dim T_Str As String

Dim Hld_Txt As Variant                      'get PDF total text into array

RW_Ct = 0                                   'set the intial value
Col_Num = 1                                 'set the intial value

Application.ScreenUpdating = False

Set AC_PD = New Acrobat.AcroPDDoc
Set AC_Hi = New Acrobat.AcroHiliteList

'set maximum selection area of PDF page

AC_Hi.Add 0, 32767

With AC_PD

    'open PDF file

    .Open PDF_File

    'get the number of pages of PDF file

    Ct_Page = .GetNumPages

    'if get pages is failed exit sub

    If Ct_Page = -1 Then
        MsgBox "Pages Cannot determine in PDF file '" & PDF_File & "'"
        .Close
        GoTo h_end
    End If

    'add sheet only one time if Data retrive in one sheet

    If Each_Sheet = False Then
        Set WS_PDF = Worksheets.Add(, Worksheets(Sheets.Count))
        WS_PDF.Name = "PDF3Text"
    End If

    'looping through sheets

    For i = 1 To Ct_Page

        T_Str = ""
        'get the page
        Set AC_PG = .AcquirePage(i - 1)

        'get the full page selection
        Set AC_PGTxt = AC_PG.CreateWordHilite(AC_Hi)

        'if text selected successfully get the all the text into T_Str string

        If Not AC_PGTxt Is Nothing Then

            With AC_PGTxt

                For j = 0 To .GetNumText - 1
                    T_Str = T_Str & .GetText(j)
                Next j

            End With

        End If


        If Each_Sheet = True Then

            'add each sheet for each page

            Set WS_PDF = Worksheets.Add(, Worksheets(Sheets.Count))

        End If

        'transfer PDF data into sheet

        With WS_PDF

            If Each_Sheet = True Then

                .Name = "Page-" & i

                'get the PDF data into each sheet for each PDF page

                'if text accessed successfully then split T_Str by VbCrLf
                'and get into array Hld_Txt and looping through array and fill sheet with PDF data

                If T_Str <> "" Then
                    Hld_Txt = Split(T_Str, vbCrLf)

                    For k = 0 To UBound(Hld_Txt)
                        T_Str = CStr(Hld_Txt(k))
                        If Left(T_Str, 1) = "=" Then T_Str = "'" & T_Str
                        .Cells(k + 1, 1).Value = T_Str
                    Next k
                        Else

                            'information if text not retrive from PDF page

                            .Cells(1, 1).Value = "No text found in page " & i
                End If

                    Else

                        'get the pdf data into single sheet

                        If T_Str <> "" Then
                            Hld_Txt = Split(T_Str, vbCrLf)

                            Yes_Fir = True

                            For k = 0 To UBound(Hld_Txt)

                                RW_Ct = RW_Ct + 1

                                'check begining of page if yes enter PDF page number for any idenfication

                                If Yes_Fir Then
                                    RW_Ct = RW_Ct + 1
                                    .Cells(RW_Ct, Col_Num).Value = "Text In Page - " & i
                                    RW_Ct = RW_Ct + 2
                                    Yes_Fir = False
                                End If

                                'check for maximum rows if exceeds start from next column

                                If RW_Ct > Li_Row Then
                                    RW_Ct = 1
                                    Col_Num = Col_Num + 1
                                End If

                                T_Str = CStr(Hld_Txt(k))
                                If Left(T_Str, 1) = "=" Then T_Str = "'" & T_Str
                                .Cells(RW_Ct, Col_Num).Value = T_Str

                            Next k

                                Else

                                    RW_Ct = RW_Ct + 1
                                    .Cells(RW_Ct, Col_Num).Value = "No text found in page " & i
                                    RW_Ct = RW_Ct + 1

                        End If

            End If

        End With
    Next i

    .Close

End With

Application.ScreenUpdating = True

MsgBox "Imported"

h_end:

Set WS_PDF = Nothing
Set AC_PGTxt = Nothing
Set AC_PG = Nothing
Set AC_Hi = Nothing
Set AC_PD = Nothing

End Sub

answered Aug 13, 2014 at 17:38

user601828's user avatar

user601828user601828

4893 gold badges7 silver badges16 bronze badges

You can use this to do something with each table in the document:

Dim oTbl As Table

For Each oTbl In ActiveDocument.Tables
    ' Do something
    Debug.Print oTbl.Columns.Count & " " & oTbl.Rows.Count
Next

You’ll need to figure out how you want the user to specify which table/tables to work with.

Something like this, perhaps:

Sub UserChosenTables()
    Dim oTbl As Table
    Dim sTemp As String
    Dim aTables() As String
    Dim x As Long

    sTemp = InputBox("Which tables", "Select tables")

    If Len(sTemp) = 0 Then ' user entered nothing
        Exit Sub
    End If

    aTables = Split(sTemp, ",")

    ' of course you'll want to add more code to CYA in case the user
    ' asks for a table that's not there or otherwise enters something silly.
    ' You might also want to let them enter e.g. ALL if they want you to do all of them
    ' (but don't know how many there are)
    For x = LBound(aTables) To UBound(aTables)
        Set oTbl = ActiveDocument.Tables(CLng(aTables(x)))
        ' do [whatever] with table here
        Debug.Print oTbl.Columns.Count & " " & oTbl.Rows.Count
    Next

End Sub

answered Jul 27, 2014 at 23:59

Steve Rindsberg's user avatar

Steve RindsbergSteve Rindsberg

14.2k1 gold badge29 silver badges34 bronze badges

4

  • Remove From My Forums
  • Question

  • Good afternoon and please excuse the interruption.

    I am looking to do the following:

    I have a 2000+ page Word document that contains a table. The table has 5 Columns (lets say they are named Column1-5 accordingly)

    The goal is to export data from the word table and import it into an excel spreadsheet. Here is the twist though. I want the macro to look for a word in Column5, if the word Patent is in there, export that row into excel, if not, dont export it. It needs to
    scan the entire table and pull out the rows where the content in Column5 has the word Patent (it can be anywhere in that cell)

    I came across a VBA code that when placed in Excel and run, will take the table created in word and export it all into excel, which is cool but I feel thats only 80% of what I need it to do.

    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

    I need it to also prompt for any doc or docx file.

    Can anyone assist?

Answers

  • Hi Storo1975,

    Actually you’re very close to the answer, just a small change of the code would meet your requirement.

    Firstly let’s say that your word document is as below:

    Modify your code like this:

    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;*.docx", , _
        "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
                    'determine if the text of the 5th column contains the word "Patent"
                  If .cell(iRow, 5).Range.Text Like "*Patent*" Then
                        'find the last empty row in the current worksheet
                        nextRow = ThisWorkbook.ActiveSheet.Range("a" & Rows.Count).End(xlUp).Row + 1
                        For iCol = 1 To .Columns.Count
                            ThisWorkbook.ActiveSheet.Cells(nextRow, iCol) = WorksheetFunction.Clean(.cell(iRow, iCol).Range.Text)
                        Next iCol
                    End If
                Next iRow
            End With
        End With
        Set wdDoc = Nothing
    End Sub

    Please take notice of the code snippet with bold font. When you run this VBA code, the final result would be like this(for table1):

    If you got anything unclear, please let me know. Thanks.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.

    Click
    HERE to participate the survey.

    • Edited by

      Friday, January 17, 2014 5:27 AM

    • Marked as answer by
      Storo1975
      Friday, January 17, 2014 3:37 PM

title ms.prod ms.assetid ms.date ms.localizationpriority

Working with tables

word

cf0858b7-6b39-4c90-552e-edb695b5cda3

06/08/2019

medium

This topic includes Visual Basic examples related to the tasks identified in the following sections.

Creating a table, inserting text, and applying formatting

The following example inserts a four-column, three-row table at the beginning of the active document. The For Each…Next structure is used to step through each cell in the table. Within the For Each…Next structure, the InsertAfter method of the Range object is used to add text to the table cells (Cell 1, Cell 2, and so on).

Sub CreateNewTable() 
 Dim docActive As Document 
 Dim tblNew As Table 
 Dim celTable As Cell 
 Dim intCount As Integer 
 
 Set docActive = ActiveDocument 
 Set tblNew = docActive.Tables.Add( _ 
 Range:=docActive.Range(Start:=0, End:=0), NumRows:=3, _ 
 NumColumns:=4) 
 intCount = 1 
 
 For Each celTable In tblNew.Range.Cells 
  celTable.Range.InsertAfter "Cell " & intCount 
  intCount = intCount + 1 
 Next celTable 
 
 tblNew.AutoFormat Format:=wdTableFormatColorful2, _ 
 ApplyBorders:=True, ApplyFont:=True, ApplyColor:=True 
End Sub

Inserting text into a table cell

The following example inserts text into the first cell of the first table in the active document. The Cell method returns a single Cell object. The Range property returns a Range object. The Delete method is used to delete the existing text and the InsertAfter method inserts the «Cell 1,1» text.

Sub InsertTextInCell() 
 If ActiveDocument.Tables.Count >= 1 Then 
  With ActiveDocument.Tables(1).Cell(Row:=1, Column:=1).Range 
   .Delete 
   .InsertAfter Text:="Cell 1,1" 
  End With 
 End If 
End Sub

Returning text from a table cell without returning the end of cell marker

The following example returns and displays the contents of each cell in the first row of the first document table.

Sub ReturnTableText() 
 Dim tblOne As Table 
 Dim celTable As Cell 
 Dim rngTable As Range 
 
 Set tblOne = ActiveDocument.Tables(1) 
 For Each celTable In tblOne.Rows(1).Cells 
  Set rngTable = ActiveDocument.Range(Start:=celTable.Range.Start, _ 
  End:=celTable.Range.End - 1) 
  MsgBox rngTable.Text 
 Next celTable 
End Sub
Sub ReturnCellText() 
 Dim tblOne As Table 
 Dim celTable As Cell 
 Dim rngTable As Range 
 
 Set tblOne = ActiveDocument.Tables(1) 
 For Each celTable In tblOne.Rows(1).Cells 
  Set rngTable = celTable.Range 
  rngTable.MoveEnd Unit:=wdCharacter, Count:=-1 
  MsgBox rngTable.Text 
 Next celTable 
End Sub

Converting existing text to a table

The following example inserts tab-delimited text at the beginning of the active document and then converts the text to a table.

Sub ConvertExistingText() 
 With Documents.Add.Content 
  .InsertBefore "one" & vbTab & "two" & vbTab & "three" & vbCr 
  .ConvertToTable Separator:=Chr(9), NumRows:=1, NumColumns:=3 
 End With 
End Sub

Returning the contents of each table cell

The following example defines an array equal to the number of cells in the first document table (assuming Option Base 1). The For Each…Next structure is used to return the contents of each table cell and assign the text to the corresponding array element.

Sub ReturnCellContentsToArray() 
 Dim intCells As Integer 
 Dim celTable As Cell 
 Dim strCells() As String 
 Dim intCount As Integer 
 Dim rngText As Range 
 
 If ActiveDocument.Tables.Count >= 1 Then 
  With ActiveDocument.Tables(1).Range 
   intCells = .Cells.Count 
   ReDim strCells(intCells) 
   intCount = 1 
   For Each celTable In .Cells 
    Set rngText = celTable.Range 
    rngText.MoveEnd Unit:=wdCharacter, Count:=-1 
    strCells(intCount) = rngText 
    intCount = intCount + 1 
   Next celTable 
  End With 
 End If 
End Sub

Copying all tables in the active document into a new document

This example copies the tables from the current document into a new document.

Sub CopyTablesToNewDoc() 
 Dim docOld As Document 
 Dim rngDoc As Range 
 Dim tblDoc As Table 
 
 If ActiveDocument.Tables.Count >= 1 Then 
  Set docOld = ActiveDocument 
  Set rngDoc = Documents.Add.Range(Start:=0, End:=0) 
  For Each tblDoc In docOld.Tables 
   tblDoc.Range.Copy 
   With rngDoc 
    .Paste 
    .Collapse Direction:=wdCollapseEnd 
    .InsertParagraphAfter 
    .Collapse Direction:=wdCollapseEnd 
   End With 
  Next 
 End If 
End Sub

[!includeSupport and feedback]

Sub OpenWord()

    Dim objWrdApp As Object, objWrdDoc As Object, avFiles, tbl As Object
    Dim var, r As Long, i As Long

          avFiles = Application.GetOpenFilename _
                («Word files(*.doc*),*.do*», 1, «Выберите таблицу», , False)
    If VarType(avFiles) = vbBoolean Then
        Exit Sub
    End If

       Set objWrdApp = CreateObject(«Word.Application»)
    objWrdApp.Visible = False
    Set objWrdDoc = objWrdApp.Documents.Open(avFiles)
    Set tbl = objWrdDoc.Tables(1)

       ‘ Копируем данные из ворд-ячейки в переменную.
    var = tbl.Cell(2, 1).Range.Text
    ‘ Удаляем с конца два символа. Эти два символа есть в каждой ворд-ячейке.
        ‘ Один символ в виде кружка, второй символ вообще не видно.
    var = Left(var, Len(var) — 2)
    ‘ Разбиваем текст ячейки на части по символу «перенос строки».
    var = Split(var, Chr(13))
    ‘ Устанавливаем курсор на эксель-листе в нужную строку.
    r = 1
    ‘ Записываем части в эксель-ячейки.
    For i = 0 To UBound(var)
        ActiveSheet.Cells(r, 1) = var(i)
        r = r + 1
    Next i

       objWrdDoc.Close True
    objWrdApp.Quit
    Set objWrdDoc = Nothing: Set objWrdApp = Nothing

   End Sub

[свернуть]

Like this post? Please share to your friends:
  • Vba цикл по ячейка в excel
  • Vba цвет диаграмм в excel
  • Vba формы для word
  • Vba формы excel что это
  • Vba форматирование таблицы word