Running MS Word macro commands in Excel macro - excel

I am trying to create an excel macro that opens Word and creates a table. I made a macro in Word to create the table and copied it into the Excel macro. When I run it, I get this error:
run-time error '450'
wrong number of argument or invalid property assignment
at the point which excel is to execute the MS Word macro (which was recorded in Word):
ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=1, NumColumns:= _
2, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
wdAutoFitFixed
EDIT: I have set references for the Word doc
' Declare the variables
Dim WordApp As Object
Dim WordDoc As Object
Dim wksSource As Worksheet
' Assign the active worksheet to an object variable
Set wksSource = ActiveSheet
' Create an instance of the Word application
Set WordApp = CreateObject("Word.Application")
' Make the Word application visible
WordApp.Visible = True
' Open the specified Word document and assign it to an object variable
Set WordDoc = WordApp.Documents.Open("C:\Users\Briet\Documents\PAJ\labels.dotm")

Make sure you've added a reference to the Word Object Lirary in your Excel VBA project.
This worked for me:
Sub Tester()
Dim wd As Word.Application
Set wd = GetObject(, "word.application") 'get reference to open Word document
wd.ActiveDocument.Tables.Add Range:=wd.Selection.Range, NumRows:=1, NumColumns:= _
2, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
wdAutoFitFixed
End Sub
Note that because Selection is a native Excel object, you need to qualify that to indicate you're referring to the Selection in Word
wd.ActiveDocument.Tables.Add Range:=wd.Selection.Range

Related

Copy value of variable in Excel 2016 macro to new doc in Word 2016

I want to insert in a W10 Excel 2016 macro some code that will
open a new Word 2016 document and
copy the value of variable "s" (string) from the Excel macro to that new Word document
then returns to the Excel macro.
Maybe it helps that I know Word can be opened with this macro:
Sub startWord()
Application.ActivateMicrosoftApp xlMicrosoftWord
End Sub
TIA for your help.
If it’s a simple copy of a string into a new Word document, then the following code should work. You haven’t indicated where you get the string from, so I’ve used the contents of cell A1 on Sheet1. You can adjust this to suit.
For the following to work, you need to enable a reference within VBA. In the VBA Editor, select Tools/References & check the box ‘Microsoft Word 16.0 Object Library’. If it’s not already checked, you’ll find it listed alphabetically.
This works for me – let me know how you go with it.
Option Explicit
Dim WordApp As Word.Application, myDoc As Word.Document, s As String
Sub CopyToWord()
On Error Resume Next
Set WordApp = GetObject(class:="Word.Application")
On Error GoTo 0
If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")
WordApp.Visible = True
WordApp.Activate
Set myDoc = WordApp.Documents.Add
s = Sheet1.Range("A1").Value
With myDoc.Content
.Text = s
End With
End Sub

Create Copy Of Excel Worksheet using Word VBA

With an already-opened workbook, I want to create a copy of a worksheet ("Template") and re-name it with the value I have in an array. When I debug the code the copy is created when I execute the line but I still get an error 424: object required.
I've tried On Error Resume Next but since I already used On Error GoTo in my sub it isn't read.
Dim oXL As Excel.Application 'Requires loading "Microsoft Excel 16.0 Object Library" from Tools -> References
Dim oWB As Excel.Workbook
Set oXL = New Excel.Application
Set oWB = oXL.Workbooks.Open(FileName:=WorkbookToWorkOn) 'Opens Excel
oXL.Visible = True 'Shows Excel window while running code. Set to false after finished editing.
Dim ws As Worksheet
For i = LBound(seller_names) To UBound(seller_names)
'On Error Resume Next 'Doesn't work
Set ws = oXL.ActiveWorkbook.Sheets("Template").Copy(After:= _
oXL.ActiveWorkbook.Sheets(oXL.ActiveWorkbook.Sheets.Count))
ws.name = seller_names(i)
Next i
Sheets.Copy doesn't return a reference to the copied sheet, so you need to first copy the sheet, then get a reference to it:
With oXL.ActiveWorkbook
.Sheets("Template").Copy After:= .Sheets(.Sheets.Count)
Set ws = .Sheets(.Sheets.Count)) '<< get the copy
ws.name = seller_names(i)
End With
On Error Resume Next should always work - but is not always a good solution - unless you have "Break on all errors" enabled in your VBA Options.

Expose Excel InlineShapes to edit

I am trying to automatize filling in a third party form from an Excel Workbook VBA module. They sadly have gone with a Word document with an in-line Excel workbook embedded, which contains cells as named ranges that I want to edit.
How do I assign the InlineShapes object to an Excel.workbook object so that I can expose it to Excel methods and properties?
This is what I have tried so far:
Sub test()
Dim wdApp As Word.Application
Set wdApp = CreateObject("word.application")
wdApp.Visible = true ' for testing
Dim wdAppendixB As Word.Document
Set wdAppendixB = wdApp.Documents.Add(ThisWorkbook.Path & "\Templates\form_template.dotx")
Dim wbAppB As Excel.Workbook
wdAppendixB.InlineShapes.Item(1).OLEFormat.Edit
Set wbAppB = wdAppendixB.InlineShapes.Item(1).OLEFormat.Object
wbAppB.Sheets("Sheet1").Range("date1").Value = "2019-06-02"
Exit Sub
As soon as the script opens the OLE object for editing, the script stops with no errors. Closing the OLE object for editing does not resume the script.
If I omit editing the object and just set the workbook object to the OLEFormat.Object it errors out with Run-time error '430' "Class does not support Automation or does not support expected interface".
Any suggestion is appreciated.
Use Activate, instead of Edit (or DoVerb with an appropriate wdOleVerb constant).
Note that this will leave the object in an activated state. There's no elegant way to emulate the user clicking outside the object to de-select it. The workarounds are to either open the object in its own window (instead of in-place) and close that file window OR to try to activate the object as a specific, non-existant class. Since this will trigger an error, this has to be wrapped in `On Error Resume Next' and 'On Error GoTo 0'.
Sub test()
Dim wdApp As Word.Application
Set wdApp = CreateObject("word.application")
wdApp.Visible = True ' for testing
Dim wdAppendixB As Word.Document
Set wdAppendixB = wdApp.Documents.Add(ThisWorkbook.Path & "\Templates\form_template.dotx")
Dim wbAppB As Excel.Workbook
Dim of As Word.OLEFormat
Set of = wdAppendixB.InlineShapes.Item(1).OLEFormat
of.Activate '.Edit
Set wbAppB = of.Object
wbAppB.Sheets("Sheet1").Range("B1").Value = "2019-06-02"
On Error Resume Next
of.ActivateAs "This.Class.NotExist"
On Error GoTo 0
End Sub

Pasting multiple linked Excel Charts to Word returning Run-Time Error 5345 Word Cannot Obtain the Data

I am trying to copy multiple Excel charts and paste them to a Word document, on separate pages, as the data type linked OLEObject but I am getting a run-time error.
Run-time error '5343':
Word cannot obtain the data for the
{00020832-0000-0000-C000-000000000046 link.
This is code that I've used in the past but literally, the only thing I changed in this code is to add an outer loop that processes the worksheets in the active workbook. Since adding that outer loop it no longer works, which is a little strange to me because I don't really see what is different.
It works for the first sheet (the currently active one), but fails when the loop moves to the next sheet. It does not matter whether the chart is pasted with or without a link.
Here is the full code for your reference:
Sub ExportingToWord_MultipleCharts()
'Declare Word Variables
Dim WrdApp As Word.Application
Dim WrdDoc As Word.Document
Dim SecCnt As Integer
'Declare Excel Variables
Dim ChrtObj As ChartObject
Dim Rng As Range
'Create a new instance of Word
Set WrdApp = New Word.Application
WrdApp.Visible = True
WrdApp.Activate
'Create a new word document
Set WrdDoc = WrdApp.Documents.Add
'Loop through each worksheet in the active workbook.
For Each WrkSht In ActiveWorkbook.Worksheets
'Loop through the charts on the active sheet
For Each ChrtObj In WrkSht.ChartObjects
'Copy the chart
ChrtObj.Chart.ChartArea.Copy
'Paste the Chart in the Word Document
With WrdApp.Selection
.PasteSpecial Link:=True, DataType:=wdPasteOLEObject, Placement:=wdInLine
End With
'Add a new page to the document.
WrdApp.ActiveDocument.Sections.Add
'Go to the newly created page.
WrdApp.Selection.GoTo What:=wdGoToPage, Which:=wdGoToNext
Next ChrtObj
Next WrkSht
End Sub
It returns the error on the following line:
'Paste the Chart in the Word Document
With WrdApp.Selection
.PasteSpecial Link:=True, DataType:=wdPasteOLEObject, Placement:=wdInLine
End With
I found a workaround, but it still doesn't explain why the error is happening. What I had to do is activate the actual worksheet in the loop.
'***ACTIVATE THE WORKSHEET IN ORDER TO REMOVE THE ERROR***
WrkSht.Activate
For whatever reason, this seemed to remove the error from popping up. However, I find this strange because when I've exported charts from PowerPoint I am not required to activate the worksheet in order to copy it. Here is the code with the adjustments, I've called out the section I added.
Sub ExportingToWord_MultipleCharts()
'Declare Word Variables
Dim WrdApp As Word.Application
Dim WrdDoc As Word.Document
Dim SecCnt As Integer
'Declare Excel Variables
Dim ChrtObj As ChartObject
Dim Rng As Range
'Create a new instance of Word
Set WrdApp = New Word.Application
WrdApp.Visible = True
WrdApp.Activate
'Create a new word document
Set WrdDoc = WrdApp.Documents.Add
'Loop through each worksheet in the active workbook.
For Each WrkSht In ActiveWorkbook.Worksheets
'***ACTIVATE THE WORKSHEET IN ORDER TO REMOVE THE ERROR***
WrkSht.Activate
'Loop through the charts on the active sheet
For Each ChrtObj In WrkSht.ChartObjects
'Copy the chart
ChrtObj.Chart.ChartArea.Copy
'Paste the Chart in the Word Document
With WrdApp.Selection
.PasteSpecial Link:=False, DataType:=wdPasteOLEObject, Placement:=wdInLine
End With
'Add a new page to the document.
WrdApp.ActiveDocument.Sections.Add
'Go to the newly created page.
WrdApp.Selection.GoTo What:=wdGoToPage, Which:=wdGoToNext
Next ChrtObj
Next WrkSht
End Sub

Can't execute word macro from excel

I simply cannot get this to work. I am trying to run a word Macro from excel (before importing a table). Here is the code:
Option Explicit
Sub RunWdMacro()
Dim WordApp As Word.Application
Dim WordDoc As Word.Document
Dim wdFileName As Variant
Set WordApp = CreateObject("Word.Application")
wdFileName = Application.GetOpenFilename("Word files ,*.doc;*.docx;*.docm", , _
"Browse for file containing table to be imported")
WordApp.Visible = True
'change TEST to the name of your macro in word
WordApp.Run "Delcolumnbreaks"
WordApp.Quit SaveChanges:=wdDoNotSaveChanges
Set WordApp = Nothing
End Sub
I am prompting for a word file to open, but it errors out at:
WordApp.Run "Delcolumnbreaks"
With error "Run-time error '-2147352573 (800200003) Can't run the specified macro. The macro is in the normal section as module 1
Any thoughts?
Thanks

Resources