Populate Excel File from Word Document Tables - VBA - excel

I'm fairly new to VBA and trying to populate a preexisting excel document based on Word Documents.
The Word Documents will have three tables, and certain cells will become the Excel columns. The idea is, every day new product information sheets come in and the Excel sheet will need to be appended. I've started by looking over this previously asked question. Do I create a macro-enabled excel sheet and run it from within Excel? Could I get the macro to look inside a directory for the word documents, and perform an iterative macro?

How about this?
Sub ImportFromWord()
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"
End Sub

That's the simplest solution. In Excel set a reference to Word in the VB Editor using Tools, References - you can then write code to manipulate Word from within Excel. You can use the keyword DIR to look for files in a folder, then declare a Word object, open the word document, iterate over the tables in the document and copy the values across to the right cells in Excel. Just watch for the ^p character that Word sticks in the cells - I tend to out the word cell's contents into a string variable and then take Left(s,len(s)-1) into excel to drop the last char.

Related

Link Excel to word document with VBA by selecting specific rows

I am trying to create a word document from an Excel sheet.
For instance, in my excel table, I have different columns. One of them has the title of "colour". I can FILTER this column by the name of the different colours (eg "blue" , "green", "yellow" etc.).
Let's say I filter my column with the colour "blue".
What I would like to do in a VBA script, is to select all these rows that have the colour "blue" in commun and copy-paste them in a word document.
I thought I had it, but with the script I am using, I do not know why, but only the titles of my different columns is pasted, regardless what I define.
Sub TestOne()
Dim appWD As Word.Application, wbXL As Excel.Workbook
Set appWD = CreateObject("Word.Application.16")
appWD.Visible = True
debut = Range("A13").End(xlUp).Row
fin = Range("A15").End(xlUp).Row
For i = debut To fin
'Copy the current row
Worksheets("Sheet1").Rows(i).Copy
'tell word to create new document.
appWD.Documents.Add
'Tell Word to paste the contents of the clipboard into the new document.
appWD.Selection.Paste
Next i
'Close the new Word document.
appWD.ActiveDocument.Close
'Save the new document with a sequential file name.
appWD.ActiveDocument.SaveAs Filename:="File"
' Close the new Word application.
appWD.Quit
Set appWD = Nothing
End Sub
If anyone has already done such a thing, or knows how to fix this script, I would be grateful for your help!

Is it possible to pass a variable from MS Word to Excel with VBA?

I have a situation where I need to pass a variable from Word to Excel via a macro. The reasoning is a little complicated, but basically I want to use this as a way to create a customized index. I point that out in case there might be an easier way to create the index. This particular index is created based on the paragraph a word or phrase is found in and not the page number. There doesn't appear to be a way to do this in Word.
So, I want to highlight the word or phrase, press my macro combo (or add a right click menu item to do it) which assigns the highlighted text to a variable and then sends it to one of three open worksheets (there will be 3 sections to the index) and adds it to the bottom row of the spreadsheet. From there I need to alphabetize the list and combine all the same phrases into one cell.
I know how to send items from Excel to Word, but when I try to research the idea of sending from Word to Excel all I can find are examples of Excel retrieving something from Word and returning it back to Excel. This is not applicable to what I'm doing. There will be thousands of index entries (before I combine them).
If it isn't possible to go directly from Word to Excel then I suppose I could send the selected text to another another document, but again I don't know how to do this.
Please help!
I did not understand why you need to work in Excel from Word, but I prepared a piece of code to show you how you can (easily) acces Excel object and work using its objects:
Sub testWorkingInExcel()
Dim objEx As Excel.Application, wb As Excel.Workbook, W As Excel.Workbook, sh As Excel.Worksheet
Dim lastEmptyRow As Long, boolFound As Boolean
On Error Resume Next
Set objEx = GetObject(, "Excel.Application") 'find Excel open session if any
If Err.Number <> 0 Then
Err.Clear: On Error GoTo 0
Set objEx = CreateObject("Excel.Application")
Set wb = objEx.Workbooks.Open("Workbook full name")
Else
For Each W In objEx.Workbooks
If W.Name = "Needed workbook" Then
Set wb = W: boolFound = True: Exit Sub
End If
Next
If Not boolFound Then Set wb = objEx.Workbooks.Open("Workbook full name")
End If
On Error GoTo 0
Set sh = wb.Worksheets("NeededSheet")
lastEmptyRow = sh.Range("A" & sh.Rows.Count).End(xlUp).Row
'Now, you have the last empty row of the needed page and you can do
'whatever you could do directly in Excel...
End Sub

Can't access correct cell when pulling value from Excel to Word Text Form Field

I am trying to pull data from Excel and place it into a word Text Form Field. The code below works except that it will not pull data from the cell I specify -- it pulls the text from a different cell. I can see that the correct cell is being selected in Excel because it is outline, but it simply does not pull the data from it. I have messed around trying different cells and with some it pulls the data I want and with others it pulls data from a different cell.
Anyone know reaons why this might be happening and how I can resolve it? Thanks.
Private Sub CommandButton1_Click()
Dim wrdApp
Dim wrdDoc
Dim Data
ActiveSheet.Cells(8, 1).Activate
Data = Selection.Cells(8, 1).Value
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Open("H:\jpmDesk\Desktop\VBA tester.docx")
With wrdDoc
wrdApp.ActiveDocument.Bookmarks("Text1").Select
wrdApp.Selection.Range.Text = Data
End With
Set wrdDoc = Nothing
Set wrdApp = Nothing
End Sub
Change
Data = Selection.Cells(8, 1).Value
to
Data = Selection.Value
Replace existing code:
ActiveSheet.Cells(8, 1).Activate
Data = Selection.Cells(8, 1).Value
With this:
Data = Range("A1").Offset(7, 0).Value
Cells(8,1).Value is not the same as Range("A1").Offset(7,0).Value
By using the offset method of the Range object, you can now retrieve values without actually selecting the cell.
Step through your code in VBE by using F8 to see how this works.

Create excel workbooks from access rows

Here is what I am trying to do. I am trying to create a workbook based on a template named by the title and to create a workbook for each row. And for the macro to loop until all rows have been depleted.
The deliverables that I want at the end are 3 excel documents named (Alpha.xlsx, Beta.xlsx, Gamma.xlsx) with the corresponding values from access plugged into their corresponding cells in their corresponding workbook. The subsequent math is there because I need to be able to manipulate the values once they are in excel.
Here is some of the research that I've found that I haven't quite been able to make much sense of due to my lack of experience coding in vba.
Links
(I can't post more than 2 so I'll keep the number of articles terse):
Research: databasejournal.com/features/msaccess/article.php/3563671/Export-Data-To-Excel.htm
Example Database/Spreadsheet:
http://www.sendspace.com/file/iy62c0
Image Album (has a picture of the database and the template in case you don't want to download):
http://imgur.com/pytPK,PY8FP#0
Any help will be much appreciated! I've been reading up and trying to figure out how to get this to work #.#
This isn't complete, but should help you get started...
Option Compare Database
Option Explicit
'Enter Location of your Template Here
Const ExcelTemplate = "C:\MyTemplate.xltx"
'Enter the Folder Directory to save results to
Const SaveResutsFldr = "C:\Results\"
Sub CreateWorkbook()
Dim SaveAsStr As String
Dim ExcelApp, WB As Object
'Create Reference to Run Excel
Set ExcelApp = CreateObject("Excel.Application")
'Create Reference to your Table
Dim T As Recordset
Set T = CurrentDb.OpenRecordset("tblData")
'Loop through all Record on Table
While Not T.BOF And T.EOF
'Open Your Excel Template
Set WB = ExcelApp.Workbooks.Open(ExcelTemplate)
'Enter your data from your table here to the required cells
WB.Worksheets("NameOfYourWorkSheet").Range("A1") = T("numValue1")
'Repeat this line for each piece of data you need entered
'Changing the Sheet name, cell range, a field name as per your requirements
'WB.Wor...
'WB.Wor...
'Save and Close the Workbook
SaveAsStr = SaveResutsFldr & T("Title") & ".xlsx"
WB.SaveAs SaveAsStr
WB.Close
Set WB = Nothing
'Move to the Next Record
T.MoveNext
Wend
'Close down the Excel Application
ExcelApp.Quit
Set ExcelApp = Nothing
End Sub

Excel macro - keep source formatting

When I try to copy data between worksheets this is no problem, but when I try to copy the same data to a word document it loses its format. Is there a way to stop this?
' Copy all data from 1.xls to new.docx
Sheets("Design").Select
Range("A1:G50").Copy
appWD.Selection.Paste
Could it be something with PasteSpecial?
Thanks.
#Brown
Select Case Range("C19").Value
Case 1
Sheets("Info").Select
Range("B7").Copy Destination:=Sheets("Design").Range("A" & x)
x = x + 2
End Select
So this copies the data from cell C19(Sheet: Info) to cell B7(Sheet: Design)
' I open my word doc etc.
Sheets("Design").Select
Range("A1:E50").Copy
appWD.Selection.Paste
This selects sheet Design, copies everything and pastes this into a word doc. I lose my formatting, I'm also using XP, office 2007.
Here is my simple test program
Sub test()
Dim wrdApp As Word.Application
Set wrdApp = New Word.Application
Dim wrdDoc As Word.Document
wrdApp.Documents.Add
Set wrdDoc = wrdApp.ActiveDocument
Range("A1:B1").Copy
wrdApp.Selection.Paste
wrdDoc.SaveAs "D:\tmp\myworddoc.doc"
End Sub
This works with Office XP (I don't have Office 2007 at hand). Cells A1:B1 contain formatted numbers. This one works fine on my machine, the created word doc contains a table with formatted numbers, too. Can you try it on yours to see if it works?

Resources