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, aWorksheet
object is declared and instantiated to the active worksheet. This object —ws
— is then used throughout the code to clearly identify allRange
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:
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 resultCol As Long
Dim tableStart As Integer
Dim tableTot As Integer
Dim ws As Worksheet
'On Error Resume Next
Set ws = ActiveSheet
ws.Range("A:AZ").ClearContents
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)
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 = 2
With ws
.Range("B1") = "Description"
.Range("B1").Font.Bold = True
.Range("C1") = "Source"
.Range("C1").Font.Bold = True
.Range("D1") = "Rationale"
.Range("D1").Font.Bold = True
End With
For tableStart = tableNo To tableTot
With .Tables(tableStart)
'copy cell contents from Word table cells to Excel cells
'''REQ
ws.Cells(resultRow, 1) = WorksheetFunction.Clean(.Cell(1, 1).Range.Text)
For iRow = 1 To .Rows.Count
'For iCol = 1 To .Columns.Count
ws.Cells(resultRow, iRow + 1) = WorksheetFunction.Clean(.Cell(iRow, 3).Range.Text)
'Next iCol
resultRow = resultRow
Next iRow
End With
resultRow = resultRow + 1
Next tableStart
End With
End Sub
-
#1
I have 100+ Word documents that I need to import into Excel
The code below from this recent thread works perfectly with the format of the Word docs we are using.
Would it be possible to modify the code to choose the folder containing the Word docs, and then import the content of each document on a new worksheet? (and name the worksheet the same name as the Word doc?)
VBA Code:
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("A4: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
Excel motto
Not everything I do at work revolves around Excel. Only the fun parts.
-
#2
Here is an example of how you can use the ‘Main’ sub below to call your sub in the OP and use the file name as a variable for your code.
VBA Code:
Sub Main()
Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject")
Dim path As String: path = "C:USERSUSERNAMEDESKTOPYOURFOLDER"
Dim fold As Object: Set fold = FSO.getfolder(path)
Dim fil As Object
For Each fil In fold.Files
yourSub fil.path
Next fil
End Sub
Sub yourSub(path)
Debug.Print path
End Sub
-
#3
Thank you lrobbo, I’m afraid that I’m not familiar enough with VBA to completely integrate the two sections of code.
Will your code also import the content of each document on a new worksheet and name the worksheet the same name as the Word doc?
-
#4
This is untested but should at least get you going in the right direction.
VBA Code:
Sub Main()
Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject")
Dim path As String: path = "C:USERSUSERNAMEDESKTOPYOURFOLDER"
Dim fold As Object: Set fold = FSO.getfolder(path)
Dim LR As Long: LR = 4
Dim fil As Object
ActiveSheet.Range("A4:AZ10000").ClearContents
For Each fil In fold.Files
ImportWordTable fil.path, LR
Next fil
End Sub
Sub ImportWordTable(docPath As String, ByRef resultRow As Long)
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 tableStart As Integer
Dim tableTot As Integer
On Error Resume Next
Set wdDoc = GetObject(docPath) '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
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
Содержание
- Copy data from Single or Multiple Tables from Word to Excel using VBA
- Tools you can use
- Extract Data from Word Document to an Excel SpreadSheet
- 1 Answer 1
- Excel VBA to import word data to excel
- 1 Answer 1
- Excel-VBA Solutions
- Pages
- Import Data from Word Table to Excel sheet
- Как из Word перевести в Excel
- Как макрос работает
- Код макроса
- Как этот код работает
- Как использовать
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
- 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.
- 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
- opens a WORD document
- searches for string «minimum stock»
- moves the cursor some lines/words further
- expands/selects the WORD cursor
- 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 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 объявляет четыре переменные: MyRange содержит целевой диапазон Excel; WD является переменной, которая предоставляет объект Application Word; wdDoc является переменной объекта, которая выставляет объект Word Document; wdRange является переменной объекта, которая выставляет объект Range Word.
- Шаг 2 копирует диапазон таблицы рабочего листа. В этом примере, диапазон жёсткий, но мы всегда можем сделать этот выбор в нечто более переменное.
- Шаг 3 открывает существующий целевой документ Word, который служит в качестве шаблона. Обратите внимание, что мы устанавливаем свойство Visible приложения Word, в True.
Это гарантирует, что мы можем увидеть действие в Word, как работает код. - Шаг 4 использует объект Range в Word, чтобы установить фокус на целевой закладке. Это по существу выбирает закладку в виде диапазона, что позволяет принимать меры в этом диапазоне.
- Шаг 5 удаляет любую таблицу, которая может существовать внутри закладки, а затем вставляет скопированный диапазон Excel. Если мы не будем удалять любые существующие таблицы, скопированный диапазон добавится к существующим данным.
- Когда вы копируете диапазон Excel в документ Word, ширина столбцов не всегда соответствуют содержанию в клетках. Шаг 6 устраняет эту проблему путем регулировки ширины столбцов. Здесь, ширина каждого столбца установлена как число, которое равно общей ширине таблицы, разделенной на число столбцов в таблице.
- Когда мы копируем диапазон Excel для целевой закладки, мы, по существу, перезаписываем закладку. Шаг 7 воссоздает закладку, чтобы гарантировать, что в следующий раз, когда вы запустите этот код, закладка будет.
- Очистка памяти
Как использовать
Для реализации этого макроса, вы можете скопировать и вставить его в стандартный модуль:
- Активируйте редактор Visual Basic, нажав ALT + F11.
- Щелкните правой кнопкой мыши имя проекта / рабочей книги в окне проекта.
- Выберите Insert➜Module.
- Введите или вставьте код.
Источник
Adblock
detector
- 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
-
Edited by
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»)
With wrdDoc
N_Of_tbles = .Tables.Count
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
MsgBox «completed»
Here is a brief explanation about the code.
You can set the visibility of the word application by assigning true or false to wrdApp.Visible
As we have set that value true in our example it will show the Word application.
Set wrdDoc = wrdApp.Documents.Open(ThisWorkbook.Path & «My document.doc»)
This will open a word file «My document.doc» which is in the same folder as the Excel file which has this code. If your file is in a different location like D:My filesMy document.doc, Then you can open the file by following code.
Set wrdDoc = wrdApp.Documents.Open(«D:My filesMy document.doc»)
In above, our word document is in closed state. What if our word document is already open. If so we can use below code.
Set wrdDoc = Documents(«My document.doc»)
This will tell you how many tables are in our word document.
Here we only import data from 1st table.
But if we want to import data from all tables, then we can use for loop to import from all of them.
wrdTbl.Columns.Count
wrdTbl.Rows.Count
above will count the number of columns and the rows of the table respectively.
And following part will put data of each cell of Word table to relavent Excel cell.
For i = 1 To RowCount
For j = 1 To ColCount
Worksheets(«sheet1»).Cells(i, j) = wrdTbl.Cell(i, j).Range.Text
Next j
Nex i