Thread: [Solved] Userform in Outlook
View Single Post
 
Old 03-16-2016, 10:40 PM
gmayor's Avatar
gmayor gmayor is offline Windows 10 Office 2016
Expert
 
Join Date: Aug 2014
Posts: 4,137
gmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud of
Default

The worksheet needs to be in XLSX format for the function to work. Also you did not include your e-mail message template. I noticed also that Outlook would not reliably start from the code so I have added a trap to ensure that Outlook is running before running the code:
Code:
Sub CreateMessageFromTemplate()
Dim olApp As Object
Dim olItem As Object
Dim olInsp As Object
Dim wdDoc As Document
Dim oRng As Range
Dim oFrm As New UserForm1
Dim strName As String, strCase As String
Dim strTo As String
Const strWorkbook As String = "D:\text.xlsx"
Const strSheet As String = "Sheet1"

    On Error Resume Next

    Set olApp = GetObject(, "Outlook.Application")
    If Err <> 0 Then
        Err.Clear
        MsgBox "Start Outlook and run the macro again"
        GoTo lbl_Exit
    End If
    On Error GoTo 0
    With oFrm
        xlFillList .ComboBox1, 1, strWorkbook, strSheet, True, True, "[Select County]"
        .Show
        If .Tag = 0 Then GoTo lbl_Exit
        strTo = .ComboBox1.Column(1)
        strName = .TextBox1.Text
        strCase = .TextBox2.Text
    End With
    Unload oFrm

    Set olItem = olApp.CreateItemFromTemplate("D:\Message.oft")
    With olItem
        .To = strTo
        .Subject = "The message subject"
        Set olInsp = .GetInspector
        Set wdDoc = olInsp.WordEditor
        Set oRng = wdDoc.Range
        With oRng.Find
            Do While .Execute(FindText:="<Name>")
                oRng.Text = strName
                oRng.Collapse 0
            Loop
        End With
        Set oRng = wdDoc.Range
        With oRng.Find
            Do While .Execute(FindText:="<Case>")
                oRng.Text = strCase
                oRng.Collapse 0
            Loop
        End With
        .Display    'This line is required
        '.Send 'Restore this line after testing
    End With
lbl_Exit:
    Set olItem = Nothing
    Set olInsp = Nothing
    Set wdDoc = Nothing
    Set oRng = Nothing
    Exit Sub
End Sub
Attached Files
File Type: zip Macro.zip (44.4 KB, 20 views)
__________________
Graham Mayor - MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com
Reply With Quote