Reputation: 815
I have a macro i wrote in vba to get selected text in an email message and for now show it in a MsgBox.
This works great when i run the macro with selected text in an email message with the email message opened in its own window.
when i try this with the text selected in the email pane of the main outlook program it gives me an error "Object variable or With block variable not set" this is coming from the "Set insp" line
any ideas?
Sub showseltext()
Dim msg As Outlook.MailItem
Dim insp As Outlook.Inspector
Set insp = Application.ActiveInspector
If insp.CurrentItem.Class = olMail Then
Set msg = insp.CurrentItem
If insp.EditorType = olEditorWord Then
Set hed = msg.GetInspector.WordEditor
Set appWord = hed.Application
Set rng = appWord.Selection
MsgBox (rng)
End If
End If
Set appWord = Nothing
Set insp = Nothing
Set rng = Nothing
Set hed = Nothing
Set msg = Nothing
End Sub
Upvotes: 1
Views: 2835
Reputation: 8033
you need to check to see if the inspector is nothing and if it is then oyu need to utilize the explorer object. Here is your code written to include that check
Sub showseltext()
Dim msg As Outlook.MailItem
Dim insp As Outlook.Inspector
If Application.ActiveInspector Is Nothing Then
If Application.ActiveExplorer.Selection.Count = 1 Then
If Application.ActiveExplorer.Selection.Item(1).Class = olMail Then
Set msg = Application.ActiveExplorer.Selection.Item(1)
End If
Else
'to many items selected
MsgBox "Please select one email"
End If
Else
Set insp = Application.ActiveInspector
If insp.CurrentItem.Class = olMail Then
Set msg = insp.CurrentItem
End If
End If
If msg Is Nothing Then
MsgBox "could not determine the mail item"
Else
If msg.GetInspector.EditorType = olEditorWord Then
Set hed = msg.GetInspector.WordEditor
Set appWord = hed.Application
Set Rng = appWord.Selection
MsgBox (Rng)
End If
End If
Set appWord = Nothing
Set insp = Nothing
Set Rng = Nothing
Set hed = Nothing
Set msg = Nothing
End Sub
Upvotes: 2