Data from word to excel vba

here’s some code making use of late binding (declare objects rather than word.application etc). From Excel 2003, it

  1. opens a WORD document
  2. searches for string «minimum stock»
  3. moves the cursor some lines/words further
  4. expands/selects the WORD cursor
  5. pastes this WORD selection into EXCEL

steps 2-5 are repeated for «Period of report:» (note that the «:» is a word boundary, so we need to jump 8 words to the right to arrive at the date)

For WORD I copied the text from your Q just as is (no table, just plain text). If you use tables instead, you may need to play with the units of the various Move statements (e.g. for cells unit:=12); the strategy remains the same: find a constant text, move cursor to final destination, expand selection, create a word range and transfer.

Both items are placed into the current cell in Excel and its right neighbor.

Sub GrabUsage()
Dim FName As String, FD As FileDialog
Dim WApp As Object, WDoc As Object, WDR As Object
Dim ExR As Range

    Set ExR = Selection ' current location in Excel Sheet

    'let's select the WORD doc
    Set FD = Application.FileDialog(msoFileDialogOpen)
    FD.Show
    If FD.SelectedItems.Count <> 0 Then
        FName = FD.SelectedItems(1)
    Else
        Exit Sub
    End If

    ' open Word application and load doc
    Set WApp = CreateObject("Word.Application")
    ' WApp.Visible = True
    Set WDoc = WApp.Documents.Open(FName)

    ' go home and search
    WApp.Selection.HomeKey Unit:=6
    WApp.Selection.Find.ClearFormatting
    WApp.Selection.Find.Execute "Minimum Stock"

    ' move cursor from find to final data item
    WApp.Selection.MoveDown Unit:=5, Count:=1
    WApp.Selection.MoveRight Unit:=2, Count:=2

    ' the miracle happens here
    WApp.Selection.MoveRight Unit:=2, Count:=1, Extend:=1

    ' grab and put into excel        
    Set WDR = WApp.Selection
    ExR(1, 1) = WDR ' place at Excel cursor

    'repeat
    WApp.Selection.HomeKey Unit:=6
    WApp.Selection.Find.ClearFormatting
    WApp.Selection.Find.Execute "Period of Report:"
    WApp.Selection.MoveRight Unit:=2, Count:=8
    WApp.Selection.MoveRight Unit:=2, Count:=3, Extend:=1

    Set WDR = WApp.Selection
    ExR(1, 2) = WDR ' place in cell right of Excel cursor

    WDoc.Close
    WApp.Quit

End Sub

You can create a button and call that sub from there, or link GrabUsage() to a function key.

I commented out the WApp.Visible = True because in production you don’t want WORD even to show up, but you will need it for debugging and playing with the cursor movements.

The disadvantage of late binding (and not using references to the Word library) is the hardcoding of units (6=story, 5=line, 2=word) instead of using Word enumerations, but I sometimes get OS crashes with early binding …. not very sexy but it seems to work.

The FileDialog object needs a reference to the MS Office Office Library. AFAIK this is standard in Excel 2003, but better to check than to crash.

And I didn’t include code to check if the items are really found; I leave this to your creativity.

Hope that helps.

Sub Import_Tables_from_Word()

Dim ws As Worksheet
Dim WordFilename As Variant
Dim Filter As String
Dim WordDoc As Object
Dim tbNo As Long
Dim RowOutputNo As Long
Dim RowNo As Long
Dim ColNo As Integer
Dim tbBegin As Integer

Set ws = Worksheets(«Analysis»)

Filter = «Word File New (*.docx), *.docx,» & _
«Word File Old (*.doc), *.doc,»

ws.Cells.ClearContents

WordFilename = Application.GetOpenFilename(Filter, , «Select Word file»)

If WordFilename = False Then Exit Sub

Set WordDoc = GetObject(WordFilename)

With WordDoc

tbNo = WordDoc.tables.Count

If tbNo = 0 Then
MsgBox «This document contains no tables»
End If

RowOutputNo = 1

For tbBegin = 1 To tbNo

With .tables(tbBegin)

For RowNo = 1 To .Rows.Count

For ColNo = 1 To .Columns.Count
ws.Cells(RowOutputNo, ColNo) = Application.WorksheetFunction.Clean(.cell(RowNo, ColNo).Range.Text)
Next ColNo
RowOutputNo = RowOutputNo + 1

Next RowNo

End With
RowOutputNo = RowOutputNo

Next tbBegin

End With

End Sub

OBJECTS
Worksheets: The Worksheets object represents all of the worksheets in a workbook, excluding chart sheets.
Range: The Range object is a representation of a single cell or a range of cells in a worksheet.

PREREQUISITES
Worksheet Name: Have a worksheet named Analysis.

ADJUSTABLE PARAMETERS
Worksheet Name: Select the worksheet where you want to import the data by changing the Analysis worksheet name in the VBA code to any worksheet in the workbook.
Message Box: Change the message that will be displayed if there are no tables in the Word document by replacing the current text in the double quotation marks «This document contains no tables».

  • 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

Содержание

  1. Copy data from Single or Multiple Tables from Word to Excel using VBA
  2. Tools you can use
  3. Extract Data from Word Document to an Excel SpreadSheet
  4. 1 Answer 1
  5. Excel VBA to import word data to excel
  6. 1 Answer 1
  7. Excel-VBA Solutions
  8. Pages
  9. Import Data from Word Table to Excel sheet
  10. Как из Word перевести в Excel
  11. Как макрос работает
  12. Код макроса
  13. Как этот код работает
  14. Как использовать

Copy data from Single or Multiple Tables from Word to Excel using VBA

Tools you can use

Copying and pasting the tables from word to excel, is easy. However, if you are using VBA to automate your Excel job, then I am sure this example would come handy.

Microsoft provides the Table object (for word) in VBA, which has a collection of methods and properties with which you to read and extract data from multiple tables in a word doc, from Excel.

Let’s see the example now.

First, create a word document (.doc or .docx) and draw a table. Add few data to it. Make the first row as header. You can draw multiple tables in your word file. Save the file.

Now, open your Excel file and add a button, an ActiveX button control, in your worksheet (Sheet1).

Press Alt+F11 to open the VBA editor. You can also right click sheet1 and choose View Code option. Add Office Object Library Reference to your application.

👉 Do you know you can copy contents (paragraphs) as it is (each word in a single cell with the same font name, size, color of the text, underline etc.) from a Word file to your Excel worksheet? Yes you can. Read this article.

Write the below code inside the CommandButton1_Click() event.

See how I am using the FileDialog object in the beginning of the procedure to select the word file. After getting access to the word file, I am creating the word and doc objects to open and read the contents in the file. The doc will remain invisible.

objWord.Visible = False ‘ Do not show the file.

The tables() method from the Table object , will allow us read the doc’s table data. The method takes a parameter as index , a number, which will return a single table object.

You can define the index values like “1”, “2”, “3” etc. depending upon the number of tables you want to read and extract data from. However, If you have multiple tables in your word file, and don’t want to add indexes manually, you can use objDoc.tables.Count to get the total tables in the file and loop through each table.

After writing the data to the Excel worksheet, I am just drawing borders around the columns and rows.

Источник

I have a requirement to extract a value from a word document on a daily basis and write it to an excel workbook. I currently do this manually and it is border line regarding the most efficient method for me

  1. Using Excel file create a vba script and add any word document references.

2 Using the word navigate to the table “9. STOCKS. ” (extracted example below – Appendix A) and read the Diesel (ltrs) daily usage highlighted in red.

3.Write this value to a spreadsheet cell.

  1. The date for this value is also key but it held in another part of the word document (Appendix B). Dates are also in the file name but we trust the internal value more than the word document name. With knowledge from points 3 and 4 extract the associated date to an adjacent spreadsheet cell.

The table is displayed below, because of the formatting I’m not able to send you the exact table but I will be able to send the values of it.

9.STOCKS (As of 00:01 hrs on Day of report issue). Stock Held Daily Usage Minimum Stock

Diesel (ltrs)
390436 15012 25000

Nitrogen (mm)
35 1 19 Champion 1033 (totes)
15 1 4 Nexguard (Boilers) 4
0.25 4 x 200 ltrs

Appendix B: Beatrice Period of Report: 00:01 – 24:00 10th August 2010

If you have any doubts regarding my question please get back to me, I appreciate your efforts and wanted to thanks in advance

1 Answer 1

here’s some code making use of late binding (declare objects rather than word.application etc). From Excel 2003, it

  1. opens a WORD document
  2. searches for string «minimum stock»
  3. moves the cursor some lines/words further
  4. expands/selects the WORD cursor
  5. pastes this WORD selection into EXCEL

steps 2-5 are repeated for «Period of report:» (note that the «:» is a word boundary, so we need to jump 8 words to the right to arrive at the date)

For WORD I copied the text from your Q just as is (no table, just plain text). If you use tables instead, you may need to play with the units of the various Move statements (e.g. for cells unit:=12 ); the strategy remains the same: find a constant text, move cursor to final destination, expand selection, create a word range and transfer.

Both items are placed into the current cell in Excel and its right neighbor.

You can create a button and call that sub from there, or link GrabUsage() to a function key.

I commented out the WApp.Visible = True because in production you don’t want WORD even to show up, but you will need it for debugging and playing with the cursor movements.

The disadvantage of late binding (and not using references to the Word library) is the hardcoding of units (6=story, 5=line, 2=word) instead of using Word enumerations, but I sometimes get OS crashes with early binding . not very sexy but it seems to work.

The FileDialog object needs a reference to the MS Office Office Library. AFAIK this is standard in Excel 2003, but better to check than to crash.

And I didn’t include code to check if the items are really found; I leave this to your creativity.

Источник

Excel VBA to import word data to excel

I am new to VBA I want to copy word tables to excel but I am not getting the REQ- part in excel, just getting other tabs

Desired output:

Output I get

1 Answer 1

A number of adjustments were necessary in order to get this to work:

On Error Resume Next has been removed. This should never be used for an entire macro — all it will do is hide errors that will tell you what’s going wrong. If errors are occurring regularly then something needs fixing! This can be used for special cases, but error handling should then be re-enabled. I see no special case in this code.

Both Word and Excel use Range , so it’s important to specify what range is meant. This is also important in Excel, alone. Relying on VBA to guess in which worksheet a range is can lead to unexpected results. For this reason, a Worksheet object is declared and instantiated to the active worksheet. This object — ws — is then used throughout the code to clearly identify all Range objects in Excel.

Since the column headings in Excel need to be written only once, that code has been moved out of the loop. Also, the first column is not labelled in the screen shot you provide (REQ). So labels should start with column B, not column A — those Range co-ordinates have been changed, accordingly.

It’s always tricky, working with Word tables that have merged cells (first column in your screen shot). So the code to get the REQ is moved outside the table cell loop and references row 1, column 1 explicitly.

The remainder of the data to be transferred is only in column 3, so there’s no need to loop columns, only rows. The column specifier for the Excel range has been modified to use irow + 1 as this gives the correct result.

The Cell( ) method in Word is: .Cell(rowIndex, colIndex)` — the parameters are reversed in the code posted in the question.

The following code works for me in my tests:

Источник

Excel-VBA Solutions

Want to become an expert in VBA? So this is the right place for you. This blog mainly focus on teaching how to apply Visual Basic for Microsoft Excel. So improve the functionality of your excel workbooks with the aid of this blog. Also ask any questions you have regarding MS Excel and applying VBA. We are happy to assist you.

Pages

Import Data from Word Table to Excel sheet

Today’s lesson is about how to import data from word table to an Excel sheet.

Here is a sample table in a word document.

Once we run the macro, It will give below result.

Below is an example code to import first table of the word document to an Excel sheet.

Remember to add a reference to the Word-library.

Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document

Set wrdApp = CreateObject(«Word.Application»)
wrdApp.Visible = True

Set wrdDoc = wrdApp.Documents.Open(ThisWorkbook.Path & «My document.doc»)
‘Use below line if document is already open.
‘Set wrdDoc = Documents(«My document.doc»)

If N_Of_tbles = 0 Then
MsgBox «There are no tables in word document»
End If

Set wrdTbl = .Tables(1)

ColCount = wrdTbl.Columns.Count
RowCount = wrdTbl.Rows.Count

‘ Loop through each row of the table
For i = 1 To RowCount
‘Loop through each column of that row
For j = 1 To ColCount
‘This gives you the cell contents
Worksheets(«sheet1»).Cells(i, j) = wrdTbl.Cell(i, j).Range.Text
Next j
Next i
End With

Set wrdDoc = Nothing
Set wrdApp = Nothing

Источник

Как из Word перевести в Excel

Что делает макрос: Если вы обнаружите, что вы постоянно копируете данные и вставляете в Microsoft Word, вы можете использовать макрос, чтобы автоматизировать эту задачу.

Как макрос работает

Перед тем как использовать макрос, очень важно к этому подготовиться. Чтобы подготовиться к процессу, вы должны иметь созданный шаблон Word . В этом документе, указать закладку, где вы хотите, чтобы ваши данные из Excel разместились.
Чтобы создать закладку в документе Word, поместите курсор в нужное место, выберите вкладку Вставка — Закладка. Это активизирует диалоговое окно Закладка, где вы назначаете имя
для закладки. После того, как назначено имя, нажмите кнопку Добавить.

Один из файлов образцов для этой части является документ под названием PasteTable.docx. Это документ представляет собой простой шаблон, который содержит одну закладку под названием DataTableHere. В этом примере кода вы скопируете диапазон к этому
шаблону PasteTable.docx, используя закладку DataTableHere, чтобы указать, где вставить скопированный диапазон.
Кроме того, необходимо установить ссылку на библиотеку объектов Microsoft Word.

Код макроса

Как этот код работает

  1. Шаг 1 объявляет четыре переменные: MyRange содержит целевой диапазон Excel; WD является переменной, которая предоставляет объект Application Word; wdDoc является переменной объекта, которая выставляет объект Word Document; wdRange является переменной объекта, которая выставляет объект Range Word.
  2. Шаг 2 копирует диапазон таблицы рабочего листа. В этом примере, диапазон жёсткий, но мы всегда можем сделать этот выбор в нечто более переменное.
  3. Шаг 3 открывает существующий целевой документ Word, который служит в качестве шаблона. Обратите внимание, что мы устанавливаем свойство Visible приложения Word, в True.
    Это гарантирует, что мы можем увидеть действие в Word, как работает код.
  4. Шаг 4 использует объект Range в Word, чтобы установить фокус на целевой закладке. Это по существу выбирает закладку в виде диапазона, что позволяет принимать меры в этом диапазоне.
  5. Шаг 5 удаляет любую таблицу, которая может существовать внутри закладки, а затем вставляет скопированный диапазон Excel. Если мы не будем удалять любые существующие таблицы, скопированный диапазон добавится к существующим данным.
  6. Когда вы копируете диапазон Excel в документ Word, ширина столбцов не всегда соответствуют содержанию в клетках. Шаг 6 устраняет эту проблему путем регулировки ширины столбцов. Здесь, ширина каждого столбца установлена как число, которое равно общей ширине таблицы, разделенной на число столбцов в таблице.
  7. Когда мы копируем диапазон Excel для целевой закладки, мы, по существу, перезаписываем закладку. Шаг 7 воссоздает закладку, чтобы гарантировать, что в следующий раз, когда вы запустите этот код, закладка будет.
  8. Очистка памяти

Как использовать

Для реализации этого макроса, вы можете скопировать и вставить его в стандартный модуль:

  1. Активируйте редактор Visual Basic, нажав ALT + F11.
  2. Щелкните правой кнопкой мыши имя проекта / рабочей книги в окне проекта.
  3. Выберите Insert➜Module.
  4. Введите или вставьте код.

Источник

Adblock
detector

As many of us want to deal with Microsoft Word Document from Excel Macro/VBA. I am going to write few articles about Word from Excel Macro. This is the first article which opens a Word Document and read the whole content of that Word Document and put it in the Active Worksheet in a particular Cell.
Opening an Word Document is more like Excel Workbook only.

To work the below code you need to Add the reference of Microsoft Word in your Excel Workbook.


Sub Copy_From_Word()

    Application.DisplayAlerts = False 'Disable all the Alerts from excel
    Application.ScreenUpdating = False 'After opening Word Doc, Document will not be visible
    'Create a New Object for Microsoft Word Application
    Dim objWord As New Word.Application
    'Create a New Word Document Object
    Dim objDoc As New Word.Document
    'Open a Word Document and Set it to the newly created object above
    Set objDoc = objWord.documents.Open("C:UsersVishDesktopNew Microsoft Office Word Document.docx")
    'To Store all the content of that word Document in a variable
    strTemp = objDoc.Range(0, objDoc.Range.End)
    'Now store that variable value in to a cell range
    Range("A1").Value = strTemp
    str1 = objDoc.Range(0, 1)
    Range("A2").Value = str1
    Range("B2").Value = strTemp
    
    objDoc.Close SaveChanges:=wdDoNotSaveChanges
    objWord.Quit
    
End Sub

Понравилась статья? Поделить с друзьями:
  • Data from web page to excel
  • Data from pdf to excel
  • Data from html to excel
  • Data from form to excel
  • Data from excel to labels