Форматирование автоматизированного файла WordHtml

Программисты Html
Ответить
Anonymous
 Форматирование автоматизированного файла Word

Сообщение Anonymous »

Я пытаюсь автоматизировать создание и отправку файла Word через Outlook, но форматирование (размер шрифта, стиль шрифта, выравнивание) не применяется.
Таблица Excel, которую я использовал, состояла всего из двух столбцов: один для электронных писем, другой для оплаты.
Этот код создает файл Word, который информирует клиента о его платеже, а затем отправляет файл через Outlook на адрес электронной почты, указанный в столбце A.
Sub SendEmail()
Dim OutlookApp As Object
Dim OutlookMail As Object
Dim ws As Worksheet
Dim rngEmails As Range
Dim cell As Range
Dim strFolderPath As String
Dim strFilePath As String
Dim fileName As String
Dim name As String

' Specify the folder path where the Word files will be saved
strFolderPath = "C:\Users\VBA\WordFiles\"

' Create Outlook application object
Set OutlookApp = CreateObject("Outlook.Application")

' Set the worksheet where email addresses and payments are located
Set ws = ThisWorkbook.Sheets("Feuil1") ' Replace "Feuil1" with the actual sheet name

' Find the last row with data in column A
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

' Loop through each cell in the range
For Each cell In ws.Range("A2:A" & lastRow)
' Check if the cell is not empty and contains a valid email address
If Not IsEmpty(cell.Value) And IsValidEmail(cell.Value) Then
' Get the payment value from column B
Dim paymentAmount As Variant
paymentAmount = ws.Cells(cell.Row, "B").Value

' Extract the name from the email address
name = Split(cell.Value, "@")(0)

' Generate the file name
fileName = "Payment_" & name & ".docx"

' Create a new Word document
Dim wordApp As Object
Set wordApp = CreateObject("Word.Application")
wordApp.Visible = False ' Set to True if you want to see Word

' Create a new document
Dim doc As Object
Set doc = wordApp.Documents.Add

' Set font size and style
With doc.Content
.Font.Size = 12
.Font.Bold = True
.ParagraphFormat.Alignment = 3 ' Center alignment
.InsertAfter "Dear " & name & "," & vbCrLf & vbCrLf
.Font.Size = 11
.Font.Bold = False
.ParagraphFormat.Alignment = 0 ' Left alignment
.InsertAfter "We are pleased to inform you that your monthly payment for the amount of $" & paymentAmount & " is ready for processing." & vbCrLf & vbCrLf
.InsertAfter "Please find the details below:" & vbCrLf & vbCrLf
.Font.Bold = True
.InsertAfter "Payment Details:" & vbCrLf
.Font.Bold = False
.InsertAfter "- Amount: $" & paymentAmount & vbCrLf & vbCrLf
.InsertAfter "Kind regards," & vbCrLf & "Your Company"
End With

' Save the document
strFilePath = strFolderPath & fileName
doc.SaveAs2 strFilePath
doc.Close

' Send email with the created Word document
Set OutlookMail = OutlookApp.CreateItem(0) ' 0 represents an email item
With OutlookMail
.To = cell.Value ' Set the recipient to the email address in the current cell
.Subject = "Monthly Payment Details" ' Set the subject of the email
.Body = "Dear " & name & "," & vbCrLf & vbCrLf & _
"Please find your monthly payment details attached." & vbCrLf & vbCrLf & _
"Kind regards," & vbCrLf & "Your Company" ' Set the email body text
.Attachments.Add strFilePath ' Attach the Word document
.Send ' Send the email immediately
End With
Set OutlookMail = Nothing

' Close Word application
wordApp.Quit
Set wordApp = Nothing
End If
Next cell

' Clean up objects
Set OutlookApp = Nothing
End Sub

Function IsValidEmail(emailAddress As String) As Boolean
' Use a regular expression to check if the email address is valid
Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
regex.Pattern = "^[\w\.-]+@[a-zA-Z\d\.-]+\.[a-zA-Z]{2,}$"
IsValidEmail = regex.Test(emailAddress)
End Function


Подробнее здесь: https://stackoverflow.com/questions/771 ... -word-file
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Html»