Pass variable from XLSM to embedded DOCM - vba

I have an embedded Word document (*.docm) in my Excel worksheet.
The Word document contains a table, that has relationship between its corresponding Table in Excel's WorkSheet.
I want count of table rows in embedded Word document been dynamically set in Document_Open event, with bellow value, from its involving Worksheet:
ThisWorkbook.Worksheets("Sheet1").ListObjects("Salary").ListRows.Count
How can I pass values between Excel (macro container document) and its embedded macro container word document? -If its a right answer for above bold issue- or another solution?
If there is another solution answer, Please note that cover need of:
Fill destination table (that is in embedded word document) cells with corresponding values from source data are in parent Table from Worksheet?, same instead of with auto generating fields with Document_Open events from macro container embedded word document.

I suggest to embed .docx document to avoid macros disabled alert each time it's opened, and to place all the code within Excel VBA Project. Here is the example, showing how to change number of rows in embedded Word document from Excel VBA:
Sub ChangeRowsCount()
Dim n As Long
With ThisWorkbook.Worksheets("Sheet1")
n = .ListObjects("Table1").ListRows.Count
With .Shapes("Object 1")
Select Case True
Case .Type <> msoEmbeddedOLEObject
MsgBox "Invalid OLE Object type"
Case InStr(1, .OLEFormat.progID, "Word.Document", vbTextCompare) <> 1
MsgBox "Invalid Application"
Case Else
.OLEFormat.Object.Verb xlVerbOpen
With .OLEFormat.Object.Object.Parent ' Word.Application
With .ActiveDocument.Tables(1).Rows
Do While .Count <> n
If .Count > n Then .Item(.Count).Delete Else .Add
Loop
End With
.Quit
End With
.Select
MsgBox "Success"
End Select
End With
End With
End Sub

Related

Finding Tables in Current Word Document

I'm trying to edit tables within a Word Document using VBA. The following MsgBox returns 0 even though there are several tables within the document. Elsewhere in the macro, I am successfully editing a value in the Word Document with:
With WA.ActiveDocument
Set myRange = .Content
With myRange.Find
.Execute Findtext:="Sally", ReplaceWith:=FirstName, Replace:=1
EndWith
EndWith
MsgBox (WA.ActiveDocument.Content.Tables.Count)
Just use inside the With statement(if they are actual tables)
MsgBox .Tables.Count
You can verify by switching to the Word document itself and putting the following Msgbox ActiveDocument.Tables.Count in the ThisDocument part of the ActiveDocument. If the answer is still 0 then you are not working with Word Tables.

Copy Word table to Excel without splitting cells

I'm struggling to paste a word table into excel without the deliminator splitting out by paragraph, as I want to grabs those paragraphs and paste into excel later.
Does anyone know how to prevent excel from splitting paragraphed text when it is pasted into excel from a word table?
Sub InputDoc()
Dim Oo As OLEObject
Dim wDoc As Object 'Word.Document
'Search for the embedded Word document
For Each Oo In Worksheets("Input").OLEObjects
If InStr(1, Oo.progID, "Word.Document", vbTextCompare) > 0 Then
'Open the embedded document
Oo.Verb xlVerbPrimary
'Get the document inside
Set wDoc = Oo.Object
'Copy the contents to cell A1
wDoc.Content.Copy
Worksheets("Paste").Range("A1").PasteSpecial Paste:=xlPasteFormats
The text you're copying has CRLF in the string and you want to avoid Excel interpreting that as multiple cells.
Just avoid using Paste and use Range.Value instead. Problem solved.
'Search for the embedded Word document
For Each Oo In Worksheets("Input").OLEObjects
If InStr(1, Oo.progID, "Word.Document", vbTextCompare) > 0 Then
'Open the embedded document
Oo.Verb xlVerbPrimary
'Get the document inside
Set wDoc = Oo.Object
'Copy the contents to cell A1
Worksheets("Paste").Range("A1").value = wDoc.Content
This will put the entire wDoc.content into one cell. That's not what you really want though. You really need to loop through the table in Word and use .Value to insert the data into Excel.

Insert text from an excel file into a word document (Word VBA)

Since my documents usually have certain phrases that can be used over and over again, I want to hotkey them all to save time. To be more specific, I plan to make, let say, Macro1 (insert "Of course"), Macro2 (insert "The issue is"), and Macro3 (insert "by the time"), hotkeyed to Alt +1,2,3 respectively. If I press Alt + 2, "The issue is" got inserted instantly at my cusor.
Here's the base macro I'm using:
Sub Macro1()
Selection.TypeText Text:="sample text"
End Sub
The problem is for any new document, the content of Macro1, 2, and 3 will often need to be changed. I plan on creating an excel file to house all the phrases for ease of edit, but don't know how to link its specific cells back to the word macros. Is there a way to do that?
Note: I'm aware of the AutoText or Building Block function in word, but I don't find them as easy to edit as an excel table.
Here is an example, assuming yor Excel file is located in "C:\temp\" and yor phrases are saved in first Worksheet and First column:
This Function will read the first cell (A1) from this excel file:
Function Read_Excel_Cell(cellRin As Long) As String
Dim oExcel As Excel.Application
Dim myWB As Excel.Workbook
Set oExcel = New Excel.Application
Set myWB = oExcel.Workbooks.Open("C:\temp\phrases.xlsx")
Read_Excel_Cell = myWB.Sheets(1).Cells(cellRin, 1)
myWB.Close
Set myWB = Nothing
Set oExcel = Nothing
End Function
And this Macro will insert it into document:
Sub InsertText1()
Selection.TypeText Text:=Read_Excel_Cell(1)
End Sub
So you can create in this way as many macros as you need and using the same function Read_Excel_Cell() you can refere to another row.
To make this running in the Word vba you must add Excel Reference (in Tools\References tick Microsoft Excel Object Library).

How to save/copy an embedded picture from Excel to Word

What I have:
An Excel file where in a column (actually it is free formatted but aligned to be within a column) some elements are embedded bmp pictures that show the formula =EMBED("Paint.Picture","") when you click on them. When you look at the Excel sheet, only the icon representing the picture is displayed, not the picture itself.
What I want:
The embedded picture (not the icon) copied to a new Word document.
The Code I have thus far:
'Image Objects
Dim myObjs As Shapes
Dim myObj As Shape
Set myObjs = ActiveSheet.Shapes
'Traversing objects
Dim row As Integer
Dim myRange As Range
Dim myRange2 As Range
Dim isAddressMatch As Boolean
'Word Document Objects
Dim wordApp As New Word.Application
Dim myWord As Word.Document
'Prepare word for output
Set myWord = wordApp.Documents.Add
wordApp.Visible = True
'Initalize traversing objectts
Set myRange = Sheets("myWorksheet").Range("Q5")
Set myRange2 = Sheets("myWorksheet").Range("E5")
row = 0
'Loop through range values in the desired column
While (myRange2.Offset(row).Value <> "")
'Loop through all shape objects until address match is found.
For Each myObj In myObjs
On Error Resume Next
isAddressMatch = (myObj.TopLeftCell.Address = myRange.Offset(row).Address)
If Err.Number <> 0 Then
isAddressMatch = False
On Error GoTo 0
End If
'When match is found copy the bmp picture from Excel to Word
If (isAddressMatch) Then
myObj.Select
''''''''This copies the excel default picture,'''''''''''''''
''''''''not the picture that is embeded.'''''''''''''''''''''
myObj.CopyPicture 'What is the correct way to copy myObj
myWord.Range.Paste
'Rest of the code not yet implement
End If
Next
row = row + 1
Wend
What happens when I run my code:
My code goes through all "shapes" that are within the bounds of the column and copies that objects picture. However, when I paste it into word, it literally made a copy of the link image (icon), and not the underlying embedded image.
What I've found thus far:
This code which shows me how to create an embedded object, but not how to copy one.
Update: Simpler solution
As specified in the comments by jspek, the image can actually be copied by using the Copy method of the OLEObject, e.g.:
Dim obj As OLEObject
Set obj = ActiveSheet.OLEObjects(myObj.Name)
'Copy the OLE object representing a picture.
obj.Copy
'Paste the picture in Word.
myWord.Range.Paste
Old solution
I've found a suboptimal solution that involves both the clipboard and SendKeys - inspired by this link. I'm quite convinced that you can do this more elegantly by exploring ways to extract the OLEObject's properties. Extracting these is beyond the scope of my expertise at this time of writing :-)
It revolves around OLEObject. This code executes the OLE object's host application (which is Paint in this case) of your picture, sends keys to copy the picture and finally, pastes it into Word.
'Get the OLE object matching the shape name.
Dim obj As OLEObject
Set obj = ActiveSheet.OLEObjects(myObj.Name)
'Activate the OLE host application.
obj.Activate
'Send CTRL+A to select the picture in Paint and CTRL+C to copy it.
Application.SendKeys "^a"
Application.SendKeys "^c"
'Paste the picture in Word.
myWord.Range.Paste
I am not a coder, but I found that if you "Define Name" for a cell range, you can do all kinds of things with the defined names. For example:
Linking Excel Workbook rows to a Word document
1. Open your Excel work book go to Formulas -> Define NAME
2. Create a "NAME" for each of the cells or groups of cells that you would like to link.
For example, I hyper-linked a Question # in a Word document to my Excel document that is used for importing questions into our Learning Management System. Example NAME = Question_22 and refers to cell range =WBT16DS058!$A$90 (=worksheet!cellrange)
3. Save & close Excel workbook.
4. Open the Word document and create your text (Question 022) , highlight and insert a hyperlink.
5. Browse & Select your Excel document, append the end of the address to include #NAME. (i.e. - R312Test.xlsx#Question_22).
6. Select the new link, and your Excel document will open to the cell range.
Because you are defining a NAME for the range of cells, the link will stay active even when the cells are moved around.
I am wondering if you used "Define Name" for your cell range that includes the picture you are trying to embed, you will have luck.
My apologies if you have already defined the cell range's name and tried this.

Error 1004 with VBA code with bookmarks

I am using a macro to populate a word document with text from named ranges in excel. The word document has bookmarks that correspond with the named excel ranges. I did not write the code, but rather copied it from another source.
There is quite a bit more to this macro than the snippet I posted. I could post the rest if that is useful. I had about half of my word document bookmarked and the macro was working fine then it suddenly stopped working.
I am receiving a error 1004 in the line highlighted below. I am a newbie so I'm not even quite sure what I should be searching for to fix this issue. Any assistance you could provide would be appreciated! Thanks in advance!
P.S. In case it's relevant, I am using Word and Excel 2007
'PASTE TEXT STRINGS LOOP
n = 1
For Each temp In BkmTxt
p = p + 1
Prompt = "Please wait. Copying text. Carrying out operation " & p & " of " & pcount & "."
Application.StatusBar = Prompt
'If The Bkmtxt(n) is empty then go to the next one, once that has been found do next operation.
If BkmTxt(n) = Empty Then
n = n + 1
'should find match and work
Else
'You might want to use multiple copies of the same text string.
'In this case you need to call the bookmark as follows: "ARTextWhatever_01"
'You can use as many bookmarks as you want.
BkmTxtSplit = Split(BkmTxt(n), "_")
vValue = Range(BkmTxtSplit(0)).Text **<----- ERROR HERE**
Set wdRng = wdApp.ActiveDocument.Bookmarks(BkmTxt(n)).Range
If Len(sFormat) = 0 Then
'replace the bookmark text
wdRng.Text = vValue
Else
'replace the bookmark text with formatted text
wdRng.Text = Format(vValue, sFormat)
End If
'Re-add the Bookmark
wdRng.Bookmarks.Add BkmTxt(n), wdRng
n = n + 1
End If
Next
Step 1: Don't copy code from external sources. Use external sources as a learning tool and try to understand what they are actually doing.
Now if I understand you correctly, you simply have an Excel sheet with named ranges, I assume they have information already within them, and a word document with bookmarks that EXACTLY match the named ranges:
Step 2: Make sure you have the word object library reference within excel
Here:
sub KeepItDoin()
dim xlRange as Excel.Range
dim wdApp as new Word.Application
dim wdDoc as Word.Document
dim wdBkm as Word.Bookmark
set wdDoc = wdApp.Documents.Open( "Filepath" ) 'get filepath from where ever
for each wdBkm in wdDoc.Bookmarks
set xlRange = Application.Range(wdBkm.Name)
wdBkm.range.text = xlRange.Value
next wdBkm
end sub
That will get you close probably (didn't test, don't care if it works. Use it to learn). The idea is that if the bookmarks match up to the range, we can use their names to find the ranges in excel and then tell excel to move the data within it into the bookmarks range.
You will likely need to add some formatting or maybe create a table and then move cell by cell in the range and fill the table but this is as close as I'm willing to get since you like to copy pasta.
In case anyone is interested, I figured it out. There was an error with the bookmarks I inserted into my Word document. This macro returns Error 1004 if the word document contains a bookmark that does not correspond to a range in excel. Thank you for your help.