2013年2月1日 星期五

[Visual Basic]Automatic Email with Word & VB



It is much easier to control Office with VB.
Rewrite my Python version to VB in 10 minutes with difficulty...
Of course, Python is still good.

============
Imports Word = Microsoft.Office.Interop.Word
Imports System.IO
Module Module1

    Sub Main()
        Dim oWord As Word.Application
        Dim oDoc As Word.Document
        Dim WordEmail_docx, Email_recipient As String
        Dim mm As Word.MailMerge

        WordEmail_docx = "F:\MyProgram\python\Word2Email\WordEmail2_template2.docx"
        Email_recipient = "F:\MyProgram\python\Word2Email\recipient.csv"

        oWord = CreateObject("Word.Application")
        oWord.Visible = True
        oWord.DisplayAlerts = False
        oDoc = oWord.Documents.Open(FileName:=WordEmail_docx)
        mm = oDoc.MailMerge
        mm.OpenDataSource(Name:=Email_recipient)

        'send the merge result to Email
        mm.MainDocumentType = WdMailMergeMainDocType.wdEMail
        mm.Destination = WdMailMergeDestination.wdSendToEmail
        mm.MailAddressFieldName = "EMail"
        mm.MailFormat = WdMailMergeMailFormat.wdMailFormatHTML
        mm.MailSubject = "This is a test mail from Python Win32---" & Format(Now, "yyyy_MM_dd_hh_mm_s")

        'merge just two record - this step may be redundant
        mm.DataSource.FirstRecord = 1
        mm.DataSource.LastRecord = 2
        mm.SuppressBlankLines = True

        'merge
        mm.Execute()

        'cleanup
        oDoc.Close()
        oWord.Quit()
        oDoc = Nothing
        oWord = Nothing


    End Sub

End Module

沒有留言: