Importing Word Tables to Excel Based on Content - vba

I'm having trouble grabbing only the tables I need into Excel. The Word Documents I'm working with consist of various tables but only the ones with certain key words need to be put into excel.
The code loops through the folder creating a worksheet for each file, but when it comes to searching the table for the key phrase, I receive an error in line 28.
I'm new to this, so any suggestions would be appreciated
Sub FormatWordTables()
Dim WB As Workbook
Set WB = ThisWorkbook
Dim BOM As Worksheet
Set BOM = WB.Sheets("BoM")
lastBOM = BOM.Range("B" & Rows.Count).End(xlUp).Row
Dim file As String
file = Dir("C:\folder\*.docx")
' create worksheet with the name of the file
Do While file <> ""
ActiveWorkbook.Sheets.Add(After:=Worksheets(Worksheets.Count)).Name = file
Dim wdDoc As Object
Set wdDoc = GetObject("C:\folder\" & file)
Dim TableNo As Long 'table number in Word
Dim iRow As Long 'row index in Excel
Dim iCol As Long 'column index in Excel
Dim tblCount As Long
With wdDoc
TableNo = wdDoc.tables.Count
For tblCount = 1 To wdDoc.tables.Count
' search through tables in Doc for specific text
With .tables(tblCount)
Dim STable As Object
Set STable = .Range(Start:=wdDoc.tables(tblCount).Cell(1, 1).Range.Start, _
End:=wdDoc.tables(tblCount).Cell(2, .Columns.Count).Range.End)
SText = "Identifying Text"
Dim Match As Range
Set Match = Nothing
Set Match = STable.Find(What:=SText)
' if text is found copy data to excel sheet
If Match <> 0 Then
For iRow = 1 To .Rows.Count
'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
.Cell(iRow, iCol).Range.Copy
ThisWorkbook.ActiveSheet.Cells(nextRow, iCol).Activate
ThisWorkbook.ActiveSheet.Paste
Next iCol
Next iRow
End If
End With
Next tblCount
End With
Set wdDoc = Nothing
file = Dir()
Loop
End Sub

Line 16 is missing the folder separator and should be:
Set wdDoc = GetObject("C:\folder\" & file)
Edit:
So you are only looking for text in the first two rows of the table. Changing your code as below should work for you.
With .tables(tblCount)
Dim STable As Range
Set STable = .Range
STable.MoveEnd wdRow, -(.Rows.Count - 2)

Related

Copying tables from Word to Excel-VBA

I am trying to copy multiple tables from a Microsoft Word Doc to Excel. The code is unable to find any tables in the word document which I think is due to the fact that the tables are located near the center of the page of each document and not near the top. Does anyone know how I can modify the code so I can successfully copy the tables?
I have tried using for loops instead of tableNo = wdDoc.Tables.Count but have had no success.
The code I have tried is from a previous thread which has been successful when the tables are located near the top of each page of the word document.
https://stackoverflow.com/a/9406983/7282657
This worked for me with your sample document. Likely there may be other scenarios where it might not work...
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
Dim allTables As Collection '<<
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
Set allTables = GetTables(wdDoc) '<<< see function below
tableNo = allTables.Count
tableTot = allTables.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 allTables(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 Sub
'extract all tables from Word doc into a collection
Function GetTables(doc As Object) As Collection
Dim shp As Object, i, tbls As Object
Dim tbl As Object
Dim rv As New Collection
'find tables directly in document
For Each tbl In doc.Tables
rv.Add tbl
Next tbl
'find tables hosted in shapes
For i = 1 To doc.Shapes.Count
On Error Resume Next
Set tbls = doc.Shapes(i).TextFrame.TextRange.Tables
On Error GoTo 0
If Not tbls Is Nothing Then
For Each tbl In tbls
rv.Add tbl
Next tbl
End If
Next i
Set GetTables = rv
End Function

VBA Multiple Word Tables to Excel - No Tables in Document

I exported all of the tables from a large Word document a few months ago, then my computer went and lost the VBA I had used...Note ++ decided to disappear and take all my files with it.
So, I have looked up several different options that are out there to pull all the tables from a Word file to Excel.
Every one I try says there are no tables in the Word file. I have tried multiple files, all the same thing.
The only other change in my environment is I upgraded to Windows 10.
I have racked my brain and cannot figure out why it is not seeing the tables?
I can copy the tables to a different word file:
Sub CopyTables()
Dim Source As Document
Dim Target As Document
Dim tbl As Table
Dim tr As Range
Set Source = ActiveDocument
Set Target = Documents.Add
For Each tbl In Source.Tables
Set tr = Target.Range
tr.Collapse wdCollapseEnd
tr.FormattedText = tbl.Range.FormattedText
tr.Collapse wdCollapseEnd
tr.Text = vbCrLf
Next
End Sub
And I can find the Table Number in the word file:
Sub FindTableNumber()
Dim J As Integer
Dim iTableNum As Integer
Dim oTbl As Table
Selection.Bookmarks.Add ("TempBM")
For J = 1 To ActiveDocument.Tables.Count
Set oTbl = ActiveDocument.Tables(J)
oTbl.Select
If Selection.Bookmarks.Exists("TempBM") Then
iTableNum = J
Exit For
End If
Next J
ActiveDocument.Bookmarks("TempBM").Select
ActiveDocument.Bookmarks("TempBM").Delete
MsgBox "The current table is table " & iTableNum
End Sub
This is an example of the VBA I have tried, and received the No Tables in Document:
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 (*.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 = 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

Copy multiple xls files data to single file using VBA

I have Multiple files in a folder.i wants to copy all Files data (i.e.all columns to new sheet) to one new sheet.
E.g. file 1 Contains 5 columns of data and file 2 contains 10 columns of data and so on. this data should copy on new sheet like first 5 columns are from file 1 and then on the same sheet from column 6, the file2 data should be copy and so on.
i tried but facing some problems like i am able to copy first file data successfully but when i am going to second file , second file data is overwriting on first file. i want second file data to the next column.
Below is my code
Public Sub CommandButton1_Click()
'DECLARE AND SET VARIABLES
Dim wbk As Workbook
Dim Filename As String
Dim Path As String
Dim mainwb As Workbook
Dim ws As Worksheet
Dim search_result As Range 'range search result
Dim blank_cell As Long
Dim wb As Workbook
Path = "C:\Test\"
Filename = Dir(Path & "*.xls")
'--------------------------------------------
'OPEN EXCEL FILES
Do While Len(Filename) > 0 'IF NEXT FILE EXISTS THEN
Set wbk = Workbooks.Open(Path & Filename)
Set wbk = ActiveWorkbook
sheetname = ActiveSheet.Name
wbk.Sheets(sheetname).Activate
Lastrow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
For i = 1 To Lastrow
wbk.Sheets(sheetname).UsedRange.Copy
Workbooks("aaa.xlsm").Activate
Set wb = ActiveWorkbook
sheetname1 = ActiveSheet.Name
Lastrow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
wb.Sheets(sheetname1).Range("A1").Select
wb.Sheets(sheetname1).Paste
Next i
ActiveCell.Offset(0, 1).Select
wbk.Close SaveChanges:=False
Filename = Dir
Loop
End Sub
plz help me......
Thanks in Advance
With the For i = 1 To Lastrow loop you are pasting the content several times and I was unable to correct it without significant change. As a result may I recommend using the below sample, I have added comments to describe what is happening.
Public Sub Sample()
Dim Fl As Object
Dim Fldr As Object
Dim FSO As Object
Dim LngColumn As Long
Dim WkBk_Dest As Excel.Workbook
Dim WkBk_Src As Excel.Workbook
Dim WkSht_Dest As Excel.Worksheet
Dim WkSht_Src As Excel.Worksheet
'Using FileSystemObject to get the folder of files
Set FSO = CreateObject("Scripting.FileSystemObject")
Set Fldr = FSO.GetFolder("C:\Users\Gary\Desktop\New folder\")
'Setting a reference to the destination worksheet (i.e. where the
'data we are collecting is going to)
Set WkBk_Dest = ThisWorkbook
Set WkSht_Dest = WkBk_Dest.Worksheets("Sheet1")
'Look at each file in the folder
For Each Fl In Fldr.Files
'Is it a xls, xlsx, xlsm, etc...
If InStr(1, Right(Fl.Name, 5), ".xls") <> 0 Then
'Get the next free column in our destination
LngColumn = WkSht_Dest.Cells(1, WkSht_Dest.Columns.Count).End(xlToLeft).Column
If LngColumn > 1 Then LngColumn = LngColumn + 1
'Set a reference to the source (note in this case it is simply selected the first worksheet
Set WkBk_Src = Application.Workbooks.Open(Fl.Path)
Set WkSht_Src = WkBk_Src.Worksheets(1)
'Copy the data from source to destination
WkSht_Src.UsedRange.Copy WkSht_Dest.Cells(1, LngColumn)
Set WkSht_Src = Nothing
WkBk_Src.Close 0
Set WkBk_Src = Nothing
End If
Next
Set WkSht_Dest = Nothing
Set WkBk_Dest = Nothing
Set Fldr = Nothing
Set FSO = Nothing
End Sub

Double loop (loop inside a loop) vba excel

I am relatively new to VBA, and am in need of some help to fully understand some issues.
I have a file with many sheets, and am in need to make a copy of the file for every team. Each file must not have the information of other teams.
I have managed to assemble this code that seems to work for one sheet, but not for every sheet that I need.
The first four sheets are supposed to remain unchanged (no filtering in these ones) and the sheet in yellow is a different arrangement from the others (I need to look at this later) but the remaining sheets have exactly the same construction, so the column to do "the math" is the same. (file in attachment with example)
Sub DeleteRowBasedOnCriteria()
'lobs names
Dim lob(14) As String
lob(0) = "AV"
lob(1) = "CA"
lob(2) = "G_13"
lob(3) = "HSTP"
lob(4) = "JLS"
lob(5) = "JR"
lob(6) = "LPV"
lob(7) = "MAO"
lob(8) = "NML"
lob(9) = "PRJ"
lob(10) = "RB"
lob(11) = "RG"
lob(12) = "SPN"
lob(13) = "VE"
'counter
Dim i As Integer
'numbers of rows
Dim rowtotest As Long
' to create a copy of the template to be filled'
Dim sFile As String 'Source file - Template'
Dim sDFile As String 'Destination file - Template'
Dim sSFolder As String 'Source folder - Template'
Dim sDFolder As String 'Destination Folder'
sSFolder = "C:\Users\Pacosta\Desktop\ParaIndividuals\team.xlsx"
MsgBox (sSFolder)
'Destination Path Window selector
Dim destinationWindow As FileDialog
Set destinationWindow = Application.FileDialog(msoFileDialogFolderPicker)
destinationWindow.Title = "Select Destination Folder"
'only select one folder
destinationWindow.AllowMultiSelect = False
If destinationWindow.Show Then
sDFolder = destinationWindow.SelectedItems(1) + "\"
End If
'copy cell content to excel file based on template with bookmarks'
Dim objExcel As Object
Dim ws As Worksheet
For i = 0 To 14
'create a file with same name as lob
sDFile = lob(i) + ".xlsx"
'Create object excel document'
Set FSO = CreateObject("Scripting.FileSystemObject")
'Copy the template do destination'
FSO.CopyFile (sSFolder + sFile), sDFolder + sDFile, True
Next i
Dim file As String
For i = 0 To 11
file = sDFolder + lob(i) + ".xlsx"
Call GetIndices(lob(i), file)
Next i
End Sub
'delete rows diferents from lobs namefile
Sub DeleteRows(lob As String, file As String)
'disable automatic calculation
Application.Calculation = xlCalculationManual
'count number of rows
Dim rowtotest As Long
'variable to work with all files
Dim ficheiro As Workbook
Set ficheiro = Workbooks.Open(file)
With ficheiro.Sheets(1)
'delete rows of the other lob's
For rowtotest = .Cells(Rows.Count, 7).End(xlUp).Row + 1 To 5 Step -1
If StrComp(.Cells(rowtotest, 7).Value, lob) <> 0 Then
.Rows(rowtotest).Delete
End If
Next rowtotest
End With
' Force a calculation
Application.Calculate
' Then remember to run automatic calculations back on
Application.Calculation = xlCalculationAutomatic
'save file
ficheiro.Save
'close file
ficheiro.Close
End Sub
Sub GetIndices(lob As String, file As String)
'count number of rows
Dim rowtotest As Long
'primeiro indice
Dim indice1 As Integer
'segundo indice
Dim indice2 As Integer
'variable to work with all files
Dim ficheiro As Workbook
Set ficheiro = Workbooks.Open(file)
With ficheiro.Sheets(1)
'delete rows of the other lob's
For rowtotest = .Cells(Rows.Count, 8).End(xlUp).Row + 1 To 5 Step -1
If StrComp(.Cells(rowtotest, 8).Value, lob) = 0 Then
indice2 = rowtotest
rowtotest = 0
End If
Next rowtotest
'delete rows of the other lob's
For rowtotest = 4 To .Cells(Rows.Count, 8).End(xlUp).Row + 1 Step 1
If StrComp(.Cells(rowtotest, 8).Value, lob) = 0 Then
indice1 = rowtotest
rowtotest = 1000
End If
Next rowtotest
Dim texto As String
texto = indice2 & ":" & .Cells(Rows.Count, 8).End(xlUp).Row + 1
.Rows(texto).Delete
texto = 5 & ":" & indice1
.Rows(texto).Delete
ficheiro.Save
ficheiro.Close
End With
End Sub
Can someone help me with this problem?
Thanks in advance.

Populate word from excel template each row=one document through bookmarks

I'm getting the error
"error 424" - object required
on the marked line:
Sub CreateWordDocuments1()
Const FilePath As String = "D:\"
Dim wApp As Word.Application
Dim wDoc As Word.Document
Set wApp = CreateObject("word.application")
wApp.Visible = True
Dim PersonCell As Range
'create copy of Word in memory
Dim PersonRange As Range
'create a reference to all the people
Range("A1").Select
Set PersonRange = Range( ActiveCell, ActiveCell.End(xlDown))
'for each person in list �
For Each PersonCell In PersonRange
'open a document in Word
Set wDoc = wApp.Documents.Open("D:\template.doc")
'go to each bookmark and type in details
CopyCell "FirstName", 1
'save and close this document
wDoc.SaveAs2 FilePath & "person " & PersonCell.Value & ".doc"
wDoc.Close
Next PersonCell
wApp.Quit
MsgBox "Created files in " & FilePath & "!"
End Sub
Sub CopyCell(BookMarkName As String, ColumnOffset As Integer)
'copy each cell to relevant Word bookmark
wApp.Selection.GoTo What:=-1, Name:="FirstName" ''' Error on this line
wApp.Selection.TypeText PersonCell.Offset(0, ColumnOffset).Value
End Sub
Also, I am trying for whole day to skip this error but I can't. I search for some alternatives such as XML maybe?
The issues with your initial code:
Main error: variable wApp exists in CreateWordDocuments1, but
not in CopyCell
Variable PersonCell exists in CreateWordDocuments1, but not in CopyCell (same as 1st)
CopyCell doesn't use parameter BookMarkName (not critical but made it redundant)
.
Edited code to accommodate multiple Word bookmarks in synch with Excel columns
Here is how all files are setup - column names in Excel represent Bookmark names in Word:
.
Option Explicit
Public Sub CreateWordDocuments()
Const FILE_PATH As String = "C:\Tmp\"
Const FILE_NAME As String = "Template"
Const FILE_EXT As String = ".doc"
Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim totalRows As Long 'assumes all columns are the same size
Dim totalCols As Long 'assumes all rows are the same size
Dim person As Long 'Outer loop counter (all rows)
Dim personList As Variant 'All data: rows and columns, without header row
Dim bookmark As Long 'Inner loop counter (all columns)
Dim bookmarks As Variant 'All bookmarks, from the header row
Set wApp = CreateObject("Word.Application")
wApp.Visible = False
'We're working in Sheet1, and data starts in its first cell (A1)
With ThisWorkbook.Worksheets(1)
With .UsedRange
bookmarks = .Rows(1).Value2 'get all column headers
totalRows = .Rows.Count
totalCols = .Columns.Count
End With
'all data without the header row -------------------------------------
personList = .Range(.Cells(2, 1), .Cells(totalRows, totalCols)).Value2
End With
For person = 1 To totalRows - 1 'each row (after header)
'Open Word Template file
Set wDoc = wApp.Documents.Open(FILE_PATH & FILE_NAME & FILE_EXT)
For bookmark = 1 To totalCols 'each column
With wApp.Selection
'bookmark name from header row
.GoTo What:=wdGoToBookmark, Name:=bookmarks(1, bookmark)
'enter data for each bookmark
.TypeText personList(person, bookmark)
End With
Next 'next column \ bookmark
With wDoc 'sava and close the new Word file (person name in column 1)
.SaveAs FILE_PATH & "Person " & personList(person, 1) & " " & personList(person, 2) & FILE_EXT
.Close
End With
Next 'next row
wApp.Quit
Set wDoc = Nothing
Set wApp = Nothing
MsgBox "Created " & totalRows - 1 & " files in " & FILE_PATH
End Sub