Simple Outlook macro to convert selected text to 'code' - vba

I'm trying to create a macro in Outlook to allow me to select text and convert that text to 'code' (Courier New, black). I'm using Outlook for Microsoft 365 which (I think) uses the Word editor...
I've copied some code I found in another answer and tweaked it, but no dice, and I fear I'm missing something obvious.
Public Sub FormatSelectedText()
Dim objItem As Object
Dim objInsp As Outlook.Inspector
Dim objWord As Word.Application
Dim objDoc As Word.Document
Dim objSel As Word.Selection
On Error Resume Next
Set objItem = Application.ActiveInspector.CurrentItem
If Not objItem Is Nothing Then
If objItem.Class = olMail Then
Set objInsp = objItem.GetInspector
If objInsp.EditorType = olEditorWord Then
Set objDoc = objInsp.WordEditor
Set objWord = objDoc.Application
Set objSel = objWord.Selection
With objSel
.Font.Name = "Courier New"
.Font.Color = RGB(0, 0, 0)
End With
End If
End If
End If
End Sub
I'm not a VBA guy, so it's likely something obvious :) I'm not even sure if it's a problem with the code or with the general macro support.
FWIW, in the past I wrote a separate VBA script to throw a warning message when I send an email to multiple people with different email domains (to avoid accidental data cross-sharing) which works fine, so I know a little bit...
To be clearer, I have added this code into a macro within the ThisOutlookSession object
I then open a new email and add some random text, select some of the text and run the macro, but the text in the email body doesn't change.

The code works correctly. You just need to add a COM reference to the Word object model to be able to use the Word object model in Outlook VBA macros.
In VBA editor window, click the “Tools” button in the menu bar.
Then, from the drop down list, select the “References” option.
The “References – Project 1” dialog box will display.
In this dialog box, you can pull the scrolling bar down until you locate what you need, in your case it is “Microsoft Word 16.0 Object Library”.
Mark the checkbox in front of the required entry and click “OK”.
Now you have added the Word object library reference successfully.

Related

Trying to recall a sent message in Outlook

I am trying to get a vba in outlook to recall the message currently selected.
the code I found is.
Option Explicit
Sub Recall()
Dim SendItem As Object
Dim olItem As Outlook.MailItem
Dim olInsp As Outlook.Inspector
'// Selected item in Sent Items folder
Set SendItem = ActiveExplorer.Selection.Item(1)
If TypeName(SendItem) = "MailItem" Then
Set olItem = SendItem
Set olInsp = olItem.GetInspector
'// Execute Recall command button
With olInsp
.Display
.CommandBars.FindControl(, 2511).Execute
.Close olDiscard
End With
End If
End Sub
I am getting an error on the line of .CommandBars.FindControl(, 2511).Execute.
How should the code be modified?
Command bars were deprecated and not used any longer. The Fluent UI (aka Ribbon UI) is used, so any old code may not work any longer. Only some methods are supported such as ExecuteMso which allows to execute buult-in ribbon controls. The CommandBars.ExecuteMso methods accepts a string which represents the identifier for the control. You need to pass the ribbon idMso value of the control instead.
CommandBars.ExecuteMso("RecallThisMessage")
But you need to make sure that such controls are available in Outlook. Message recall is available after you click Send and is available only if both you and the recipient have a Microsoft 365 or Microsoft Exchange email account in the same organization. So, for example, a message sent to or from a Hotmail, Gmail, or live.com account can't be recalled.

How to clear all formatting from body text in Outlook

I didn't find this question anywhere, so I don't if it's even possible because we can't record macro in Outlook.
But, I'd like to clear all text formatting in my e-mail that I'm replying by a macro in Outlook.
Since I'm using olReply.HTMLBody and building all the body with a Loop and some if and elses, I couldn't format the body in it.
Example:
Clear all text formatting - Outlook
Thanks!
I'm not sure how your code looks like but here is quick example using ClearFormatting Method Make sure you click Reply or ReplyAll and select the text you are trying to format then run the code
Option Explicit
Public Sub Exmple()
Dim wDoc As Word.Document
Dim rngSel As Word.selection
If Application.ActiveInspector.EditorType = olEditorWord Then
Set wDoc = Application.ActiveInspector.WordEditor ' use WordEditor
Set rngSel = wDoc.Windows(1).selection ' Current selection
rngSel.ClearFormatting
End If
Set wDoc = Nothing
End Sub

Referencing already opened word document in VBA

I am using Excel VBA to open a word Template and it populates the template with information from an excel spreadsheet. From there, I have a button on the spreadsheet that I want to then populate another line in the word document whenever it is clicked. The problem I am encountering is that when I run the button macro it just opens up another word document and pastes the button information instead of doing it on the already opened document. I will attach my code below and I believe it is an easy fix I just can't seem to find a way around it.
Sub RepairCal()
Dim objWord As Object
Dim objDoc As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.Documents.Open("C:\Users\z003narc\Documents\Gage Lab Form Template.docm")
objWord.Activate
With Selection
objWord.ActiveDocument.Selection.MoveDown count:=6
objWord.ActiveDocument.Selection.MoveRight count:=5
objWord.ActiveDocument.Selection.TypeText Text:="Repair and Calibration"
End With
End Sub
Try this:
With objWord
.Selection.MoveDown count:=6
.Selection.MoveRight count:=5
.Selection.TypeText Text:="Repair and Calibration"
End With
Are you saying you already have the document open when you run this every time? The way you wrote the code, it will do this:
1) Open new blank Microsoft Word process
2) In the new process, opens the workbook you have chosen
3) Makes the new process the active window
4) does stuff
If you want it to attach to the file you already have open, you would need to do GetObject instead of CreateObject. So change:
Set objWord = CreateObject("Word.Application")
To
Set objWord = GetObject(, "Word.Application")
This will attach to the currently open process, then open the workbook in that process. However, it will still open up a fresh copy of that document each time, because that's what you're telling it to do.

VB.Net working with ActiveDocument in an already running instance of word

I have a small VB.Net application which opens a new word document from a template (opens as Document1.docx for example). It runs some code to find a replace some text.
It then allows the user to edit the open document. There is a small winform open with a button called 'Complete'. When the user clicks this, I want it to save the document and do some further editing etc.
However, I cannot get the code to work to see the active document in the running instance of Word.
Whenever I refer to the activedocument, it throws and exception saying there are no documents open.
The code which is looking to save the active document is in a separate sub from where the Word.Application object is created. Word is running with the document open but it still fails.
I've tried the following to make sure it is getting the instance of word that is open;
WordApp = Marshal.GetActiveObject("Word.Application")
But is still does not see any open documents.
Any suggestions?
EDIT #1 - Sorry for not including the code;
This is the code that starts Word and does some basic find/replace. It then starts form3 which stays in place whilst the user edits the word document. This code runs from a button click on form 2;
Dim oWord As Word.Application
Dim oDoc As Word.Document
Dim path As String
path = "C:\Templates/"
Try
oWord = CreateObject("Word.Application")
oWord.Visible = True
Catch ex As Exception
''Some error handling code not included for the purpose of StackOverflow
End Try
Try
oDoc = oWord.Documents.Add(path & "MG11.dot")
Catch ex As Exception
''Some error handling code not included for the purpose of StackOverflow
End Try
With oWord.Selection.Find
''Find & Replace Code - this works so is not included for Stackoverflow
End With
Form3.Show()
Me.WindowState = FormWindowState.Minimized
Form1.WindowState = FormWindowState.Minimized '(form 1 has no code which effects Word)
End Sub
Form 3 has one button, which when pressed should save the word document. It will give it a filename based on info from elsewhere. Only the basic code is shown here - I just need to get vb.net to see the active document for now. This code is ran on Button_1 Click for Form 3.
Dim WordApp As Word.Application
Dim oDoc As Word.Document = WordApp.ActiveDocument
oDoc = WordApp.ActiveDocument
I've also tried;
Dim WordApp As Word.Application
WordApp = Marshal.GetActiveObject("Word.Application")
Dim oDoc As Word.Document
oDoc = WordApp.ActiveDocument
'once oDoc is set properly I will use SaveAs2 to handle the saving etc
It fails on WordApp.ActiveDocument, stating there are no open documents.
Either make sure oWord is in scope in your Form3. It might already be in scope or you add a Public Word.Applications property to your Form3 and set that property before showing the form.
In the first case you access the ActiveDocument on the existing oWord object in scope, in the second you set the property on the form and access that before showing.
oWord.ActiveDocument

Close/Release Word object in VBA?

I have the following code to open the manual for an Excel Workbook application I have developed:
Sub OpenManual()
'Word.Application.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"
End Sub
This gives me 2 issues though:
The document opens, but in the background. The user doesn't know the document has opened unless they know to check Microsoft Word in the Taskbar.
When I try to close the word document I receive:
This file is in use by another application or user. (C:\Users\Me\AppData...\Normal.dotm)
When I click ok on that dialogue, I receive a "Save As" screen.
If I cancel out of that and try to close the blank Microsoft Word instance I then get:
Changes have been made that affect the global template, Normal. Do you want to save those changes?
Then if I click No, everything finally closes.
Can anyone help me out with these 2 issues? Do I need to release the object somehow? Have never seen this before.
EDIT:
After trying #Layman-Coders method:
Sub OpenManual()
'Word.Application.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"
'Open an existing Word Document from Excel
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
' Should open as the forefront
objWord.Activate
'Change the directory path and file name to the location
'of the document you want to open from Excel
objWord.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"
objWord.Quit
Set objWord = Nothing
End Sub
When I have one other word document open and click the button, the following occurs:
Manual opens in the forefront, but I immediately receive This file is in use by another application or user. (C:\Users\Me\AppData\...\Normal.dotm)
I press OK and receive the Save As dialogue.
Cancel out of the Save As dialogue and am presented my Manual document.
When I click the Red X to close the document, I receive Changes have been made that affect the global template, Normal. Do you want to save those change? I click No and the document closes.
If this document is the first instance of word I have opening:
The document opens.
As soon as code hits the objWord.Quit line the document immediately closes.
I am just wanting the document to open to the forefront allowing users to view the Manual for assistance when they need it, and let them close the document at their discretion.
So the problem you are having with Word asking you to save the global template is because there is already a copy Word open which has rights to the Normal template. When you use CreateObject to set your Word object you are loading up Word a second time which opens Normal template as read only.
What you need to do is check if Word is open or not and if it is grab that copy of Word. If it's not then you can open up Word.
Sub OpenManual()
Dim objWord As Object
'We need to continue through errors since if Word isn't
'open the GetObject line will give an error
On Error Resume Next
Set objWord = GetObject(, "Word.Application")
'We've tried to get Word but if it's nothing then it isn't open
If objWord Is Nothing Then
Set objWord = CreateObject("Word.Application")
End If
'It's good practice to reset error warnings
On Error GoTo 0
'Open your document and ensure its visible and activate after openning
objWord.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"
objWord.Visible = True
objWord.Activate
Set objWord = Nothing
End Sub
One other nice line of code is to surpress display alerts. This will stop the 'do you want to save' type dialog boxes from appearing.
objWord.DisplayAlerts = 0
Try something like this:
Sub OpenManual()
'Word.Application.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Activate 'Should make it the forefront (1)
objWord.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"
'If you just want to close it afterwards...
objWord.Quit 'Changes are discarded
'Either way, you should have the following somewhere
Set objWord = Nothing
End Sub
Setting the object to nothing should eliminate the connection
I had the same problem. And only code below closed this Word window:
Dim X As Variant
X = Shell("powershell.exe kill -processname winword", 1)
I found this code in one of the answers Closing word application from excel vba