We use Outlook calendar to keep track of room bookings at our local community centre. For each calendar appointment/room booking we insert an object from file (an excel spreadsheet). The spreadsheet and file path is the same for each booking. Screenshot
I'd like to simplify embedding this spreadsheet with a macro. Unfortunately Outlook doesn't allow me to record one, so I'm trying to get to grips with scripting it with VBA. I tried recorded the macro in Word to see if it would copy over to Outlook (it doesn't - object variable not set). The code generated by Word was
Selection.InlineShapes.AddOLEObject ClassType:= _
"Excel.SheetMacroEnabled.12", FileName:= _
"K:\OutlookCalendar.xlsm" _
, LinkToFile:=False, DisplayAsIcon:=False
I think I need to specify DIMs, but I'm getting out of my depth and I've been unable to find a Google solution so far. Could someone point me in the right direction please?
First set a reference to the "Microsoft Word x.0 Object Library" so Outlook can recognize the objects used by Word - Click Tools/References
Now In order to use your recorded macro in Outlook, you need to set a variable to the Selection object Item.
Example
Option Explicit
Public Sub UseWord()
Dim Inspector As Outlook.Inspector
Dim wdDoc As Word.Document
Dim Selection As Word.Selection
Set Inspector = Application.ActiveInspector()
Set wdDoc = Inspector.WordEditor
Set Selection = wdDoc.Application.Selection
'-> And insert your recorded macro here
End Sub
IDE Tools / References
Related
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).
I'm writing a PowerPoint macro that opens a Word document and imports every picture in the document to its own slide. Because I can't place the Word InlineShape objects directly in PowerPoint, apparently, I'm using the clipboard. The relevant code is:
Dim wdApp As Object
Dim SourceDoc As Document
Dim TargetSlide As Slide
Dim Figures As Word.InlineShapes
Dim Figure As Word.InlineShape
Dim TargetShapeRange As ShapeRange
Set wdApp = CreateObject("Word.Application")
Set SourceDoc = wdApp.Documents.Open(FileName:=PathToFile, ReadOnly:=True)
Set Figures = SourceDoc.InlineShapes
For Each Figure In Figures
Figure.Range.Select
Figure.Application.Selection.Copy
Set TargetSlide = ActivePresentation.Slides.AddSlide(ActivePresentation.Slides.Count + 1, _
ActivePresentation.SlideMaster.CustomLayouts(6))
Set TargetShapeRange = TargetSlide.Shapes.Paste
Next Figure
With PowerPoint 2010 and Word 2010, this works perfectly. In PowerPoint 2013 (with Word 2013 installed, and referencing the Microsoft Word 15.0 Object Library rather than 14.0), the Set TargetShapeRange = TargetSlide.Shapes.Paste line gives me run-time error '-2147188160 (80048240)':
Shapes (unknown member): Invalid request. Clipboard is empty or contains data which may not be pasted here.
I've tried using the Copy and CopyAsPicture methods on both the Selection and Range objects. I've tried using the Shapes.PasteSpecial command. I've tried several different ways of accessing the Word Application object. Nothing works.
Notably, if I modify the code to copy the preceding paragraph of text in addition to the picture, the script works—it retrieves the text, but not the picture.
I know this question is almost two years old but I found this through google after having a similar issue so I'll post this here.
Try
Figure.Application.ActiveWindow.ScrollIntoView Selection.Range, True
right before copying. It works for me even with screenupdating disabled or if the application is not visible.
I'm completely new to VBA, especially across different programs, but I have created myself a little real-world task that quickly got complicated, someone could give me some pointers or code snippets to try out to achieve the following:
I have an Excel file that's filled with names and numbers (see below) and I would like to transfer them individually to a Word document.
If I have highlighted cell A2 and click on [BUTTON], I want Word to open automagically and type out something like
--"Hi Mike, your current amount is $12.37 and you live in 23 One Street. Thanks."--
The amount should be printed in bold, and after that Word should save the file and close itself without further input needed.
Similarly, when I have selected A3, it should open another document, write the same text but with Julia's variables filled in, save it to a specified location and close.
A B C
1 Name Address Amount
2 Mike 23 One Way $12.37
3 Julia 3949 Street $39.23
[BUTTON]
So essentially, I guess, I'm trying to "remote-control" Word from within Excel and feed some variables from Excel into Word. I am at a complete loss how to do that, to be honest.
What I have found so far is this:
Dim wdApp As Word.Application, wdDoc As Word.Document
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then 'Word isn't already running
Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0
Set wdDoc = wdApp.Documents.Open("C:\temp\[NAME AFTER SELECTED FIELD A2].docx")
wdApp.Visible = True
...
Now I don't know what to do!
How to pass the standard text with the variables from the row of the selected field over to Word?
How to format them (bold, Arial, red, etc.)?
How to save under the specified filename?
Is this even possible to do? I know VBA is very powerful, so I hope you can help me out!
I'm using Office 2013, so any caveats related to macro programming or VBA language should take that into account.
Thank you so much!
Don't use get/create object. My macros are all coded as follows:
dim wdApp as New Word.Application 'Always use a new instance
Set wdDoc = wdApp.Documents.Open("C:\temp\[NAME AFTER SELECTED FIELD A2].docx")
wdApp.visible = true
From there you simply work as you would in word. Passing variables is pretty simple as the datatypes exist on both sides (double, integer, string etc are all included in the standard VBA libraries that are included by default so no need to add references). So if I want to tell word to add a paragraph:
wdDoc.paragraphs.add
wdDoc.paragraphs(wdDoc.paragraphs.count).range.text = "Hello World!"
Want to add text from a specific range?
dim xlRange as Excel.Range
dim wdApp as New Word.Application 'Always use a new instance
Set wdDoc = wdApp.Documents.Open("C:\temp\[NAME AFTER SELECTED FIELD A2].docx")
wdApp.visible = true
set xlRange = activesheet.range("A1") 'Just as an example
wdDoc.paragraphs.add
wdDoc.paragraphs(wdDoc.paragraphs.count).range.text = xlRange.value
Finally, say you want to use a variable name form excel to open a specified word document:
dim name as string
name = selection.cells(1).value 'Assuming they selected the cell
dim wdApp as New Word.Application 'Always use a new instance
Set wdDoc = wdApp.Documents.Open("C:\temp\" & name & ".docx")
wdApp.visible = true
I know this is a year late, but hey, hope it helps.
As a final note:
Use exit sub just prior to end sub in the word macro. Exit sub returns to caller where as end sub does not.
sub test
'do the word stuff
exit sub 'Stop it short of end sub
end sub
You could do this but it would be quite difficult.
Much easier is to use your spreadsheet from Work.
In Word (2013) go to the Design ribbon, and use the Start Mail Merge wizard. The source of addresses will be your spreadsheet. I think this will be much easier than what you are planning.
Cheers -
I am trying to automatically update certain information (such as names, dates and numbers) across 3 different Word documents by putting the data into a spreadsheet and linking to the respective cells from Word. The spreadsheet has some Macros in it which auto-update parts of the spreadsheet internally.
Everything is working fine, except for updating the links in the Word documents.
When trying to update a link in Word by right-clicking on it and selecting the "update link" option it brings up the Macro warning dialog for the spreadsheet, asking whether I want to activate Macros or not. It doesn't do this just once but constantly during the 20s or so the update process takes (which seems unusually long to me). So updating the link works, but only if you're willing to click the "activate Macros" button of a few dozen times.
I tried to automate updating all fields in a document from Word with VBA, but that has the same problem, it also brings up the Macros dialog constantly for half a minute.
Here's my code for that:
Sub UpdateFields()
ActiveDocument.Fields.Update
End Sub
I also tried to update the Word documents directly from the spreadsheet, but that does not work either, because when Excel tries to open a Word document via VBA the program stops executing and trows this error:
"Excel is waiting for another application to complete an OLE action."
Clicking ok and waiting does not help because the error message reappears after a few seconds, and the only way to stop it is to manually kill the Excel process.
Here's my Excel Macro code:
Sub LoopThroughFiles()
Path = Application.ActiveWorkbook.Path
Dim WordFile As String
WordFile = Dir(Path & "\*.doc")
Do While Len(WordFile) > 0
Run Update(Path & "\" & WordFile)
WordFile = Dir
Loop
End Sub
Function Update(Filepath As String)
Dim WordDoc As Word.Document
Set WordApplication = CreateObject("Word.Application")
Set WordDoc = WordApplication.Documents.Open(Filepath) 'This produces the error
ActiveDocument.Fields.Update
End Function
Note that the only files in the folder are the 3 documents and the spreadsheet, and the program does find the files without any problems.
I have searched for solutions online but I did not really find anything, which I found odd, since it seems like a pretty common thing that someone would do with VBA.
Then again, I have very little experience with VBA, so I might be completely missing the point and there is a super simple solution I am just not aware of.
I think I see the error, which is a silent failure, becuase the document contains links, there is an open dialog waiting for you to say "yes" or "no" to update the links.
We can suppress this dialog by disabling the automatic link updates (WordApplication.Options.UpdateLinksAtOpen = False).
Function Update(Filepath As String)
Dim WordApplication As Word.Application
Dim WordDoc As Word.Document
Dim updateLinks As Boolean
Set WordApplication = CreateObject("Word.Application")
updateLinks = WordApplication.Options.UpdateLinksAtOpen 'capture the original value
WordApplication.Options.UpdateLinksAtOpen = False 'temporarily disable
Set WordDoc = WordApplication.Documents.Open(Filepath)
WordDoc.Fields.Update
'MsgBox "Links updated in " & WordDoc.Name
'## Save and Close the Document
WordDoc.Save
WordDoc.Close
'## reset the previous value and Quit the Word Application
WordApplication.Options.UpdateLinksAtOpen = updateLinks '
WordApplication.Quit
End Function
Also, remember to Save and Close the document, and Quit the word application inside the function.
I made this other modification:
In your function, ActiveDocument is not an object in Excel, so you would need to qualify it, otherwise that line will also throw an error. Rather than refer to WordApplication.ActiveDocument, I just simply refer to the WordDoc which you have already assigned.
I am trying to do some relatively simple copy and pasting from Excel 2007 into Word 2007. I've looked through this site and others, and keep getting hung up on the same thing- the third line n the code below keeps giving me the "User type note defined" error msg. I am really confused since I just lifted this from another solution (and had similar issues with other solutions I tried to lift). Could someone please educate me on what is causing the error, and why?
Sub ControlWord()
' **** The line below gives me the error ****
Dim appWD As Word.Application
' Create a new instance of Word & make it visible
Set appWD = CreateObject("Word.Application.12")
appWD.Visible = True
'Find the last row with data in the spreadsheet
FinalRow = Range("A9999").End(xlUp).Row
For i = 1 To FinalRow
' Copy the current row
Worksheets("Sheet1").Rows(i).Copy
' Tell Word to create a new document
appWD.Documents.Add
' Tell Word to paste the contents of the clipboard into the new document
appWD.Selection.Paste
' Save the new document with a sequential file name
appWD.ActiveDocument.SaveAs Filename:="File" & i
' Close this new word document
appWD.ActiveDocument.Close
Next i
' Close the Word application
appWD.Quit
End Sub
This answer was mentioned in a comment by Tim Williams.
In order to solve this problem, you have to add the Word object library reference to your project.
Inside the Visual Basic Editor, select Tools then References and scroll down the list until you see Microsoft Word 12.0 Object Library. Check that box and hit Ok.
From that moment, you should have the auto complete enabled when you type Word. to confirm the reference was properly set.
As per What are the differences between using the New keyword and calling CreateObject in Excel VBA?, either
use an untyped variable:
Dim appWD as Object
appWD = CreateObject("Word.Application")
or
Add a reference to Microsoft Word <version> Object Library into the VBA project via Tools->References..., then create a typed variable and initialize it with the VBA New operator:
Dim appWD as New Word.Application
or
Dim appWD as Word.Application
<...>
Set appWd = New Word.Application
CreateObject is equivalent to New here, it only introduces code redundancy
A typed variable will give you autocomplete.