Pass multiple entries between Userforms on VBA - forms

So I am trying to a create userform. I currently have two forms, the first is general data for a truck, once the user has entered all the appropriate text box's the second userform will display and transfer the data onto the Truck Info label for reference. (I got this transfer figured out)
1st User Form
I want the user to have the ability to add multiple part numbers & qty for each specific/Unique trailer (usually have more than 1 part). So when the user clicks the "Add Part Number" Button it will add a new row into the details and return focus to Part number Combo Box like I did with the first user form so they can start on the next part
2nd Form
Here is my code for the 1st form
Private Sub UserForm1_Initialize()
txtTrailerNum.SetFocus
txtTrailerNum.Value = ""
txtScacCode.Value = ""
txtTruckNum.Value = ""
txtSupNum.Value = ""
txtInvoiceNum.Value = ""
txtInvoiceType.Value = ""
txtOrgRef.Value = ""
End Sub
Private Sub Clear_btn_Click()
txtTrailerNum.Value = ""
txtScacCode.Value = ""
txtTruckNum.Value = ""
txtSupNum.Value = ""
txtInvoiceNum.Value = ""
txtInvoiceType.Value = ""
txtOrgRef.Value = ""
End Sub
Private Sub Enter_btn_Click()
If txtTrailerNum.Text = "" Then
MsgBox "Please Enter a valid Trailer Number."
txtTrailerNum.SetFocus
Exit Sub
End If
If txtScacCode.Text = "" Then
MsgBox "Please Enter a valid SCAC Code."
txtScacCode.SetFocus
Exit Sub
End If
If txtTruckNum.Text = "" Then
MsgBox "Please Enter a valid Truck Number."
txtTruckNum.SetFocus
Exit Sub
End If
If txtSupNum.Text = "" Then
MsgBox "Please Enter a Supplier Number."
txtSupNum.SetFocus
Exit Sub
End If
If txtInvoiceNum.Text = "" Then
MsgBox "Please Enter a valid Invoice Number."
txtInvoiceNum.SetFocus
Exit Sub
End If
If txtInvoiceType.Text = "" Then
MsgBox "Please Enter a valid Invoice Number."
txtInvoiceType.SetFocus
Exit Sub
End If
If txtOrgRef.Text = "" Then
MsgBox "Please Enter a valid Oiginator Reference."
txtOrgRef.SetFocus
Exit Sub
End If
UserForm2.Show
End Sub
Here is the code for my 2nd Form
Private Sub AddPrtNumbtn_Click()
End Sub
Private Sub PartNumcbo_AfterUpdate()
On Error Resume Next
txtPartDesc=Application.WorksheetFunction.VLookup(PartNumcbo.Value,
Range("PartDesc"), 2, False)
If Err.Number <> 0 Then
MsgBox "Invalid Part Number"
txtPartDesc.Value = ""
End If
On Error GoTo 0
End Sub
Private Sub UserForm_Initialize()
PartNumcbo.RowSource = "PartDescData!A:A"
TruckInfolbl.Caption = "Trailer Num: " & UserForm1.txtTrailerNum.Value & "
" & "SCAC Code: " & UserForm1.txtScacCode.Value & " " & "Truck Number: " &
UserForm1.txtTruckNum.Value & " " & "Supplier Number: " &
UserForm1.txtSupNum.Value & " " & "Invoice Number: " &
UserForm1.txtInvoiceNum & " " & "Invoice Type: " &
UserForm1.txtInvoiceType.Value & " " & "Originator Reference: " &
UserForm1.txtOrgRef.Value
End Sub
Ideally when the form is completed the part numbers would be related to the truck from the first form and then input onto a worksheet range. So if the user clicked the create trailer button on the bottom of the 2nd form this would be input into a worksheet.
How would I go about passing data from the combo box and two txtboxes on the 2nd Userform to the Inventory Details Label, and then input that into a range???

One form will be parent and one child. Parent will have reference to child and will create it. When child is finished with its work it will raise an event with all the data it has collected etc. Parent will subscribe to this event and so it will receive the data.
Note:
As #Comintern suggest it might be appropriate to wrap all the data in a class and pass instance of this class.
Here an example, HTH.
Parent Form
Option Explicit
Private WithEvents m_childForm As UserFormChild
Private Sub CommandButton1_Click()
Set m_childForm = New UserFormChild
m_childForm.Show
End Sub
Private Sub m_childForm_ProcessData(ByVal comboBoxData As String, ByVal textBoxData1 As String, ByVal textBoxData2 As String)
Me.TextBox1.Text = "Data: " & comboBoxData & ", " & textBoxData1 & ", " & textBoxData2
End Sub
Child Form named UserFormChild
Option Explicit
Public Event ProcessData(ByVal comboBoxData As String, ByVal textBoxData1 As String, ByVal textBoxData2 As String)
Private Sub CommandButton1_Click()
RaiseEvent ProcessData(Me.ComboBox1.Text, Me.TextBox1.Text, Me.TextBox2.Text)
Unload Me
End Sub
Private Sub CommandButton2_Click()
Unload Me
End Sub
Private Sub UserForm_Initialize()
Me.ComboBox1.AddItem "A"
Me.ComboBox1.AddItem "B"
Me.ComboBox1.AddItem "C"
Me.ComboBox1.ListIndex = 1
End Sub

Related

Getting Email Addresses for Recipients (Outlook)

I have a code that I was able to string together that logs my sent emails into an excel sheet so i can use that data for other analysis.
In it, I have it resolving the name into an email as outlook shortens it ("Jimenez, Ramon" = email#address.com) as outlook configured this and it works when i send an email to anyone in my company as they are in my address book.
Now, when I email anyone outside it defaults to lastName, firstName so it is not converting this and logging it.
I thought the code I have in here already does this, but I guess not. I have already come this far and I am NOT a software guru at all. Does anyone have insight on how I can also include this as well?? Please see code below:
Private WithEvents Items As Outlook.Items
Const strFile As String = "C:\Users\a0227084\Videos\work\test.xlsx"
Private Sub Application_Startup()
Dim OLApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set OLApp = Outlook.Application
Set objNS = OLApp.GetNamespace("MAPI")
' default local Inbox
Set Items = objNS.GetDefaultFolder(olFolderSentMail).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error GoTo ErrorHandler
Dim Msg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
' ******************
FullName = Split(Msg.To, ";")
For i = 0 To UBound(FullName)
If i = 0 Then
STRNAME = ResolveDisplayNameToSMTP(FullName(i))
Call Write_to_excel(CStr(Msg.ReceivedTime), CStr(Msg.Subject), CStr(STRNAME))
ElseIf ResolveDisplayNameToSMTP(FullName(i)) <> "" Then
STRNAME = ResolveDisplayNameToSMTP(FullName(i))
Call Write_to_excel(CStr(Msg.ReceivedTime), CStr(Msg.Subject), CStr(STRNAME))
End If
Next i
'Call Write_to_excel(CStr(Msg.ReceivedTime), CStr(Msg.Subject), CStr(STRNAME))
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
Sub tes2t()
End Sub
Function getRecepientEmailAddress(eml As Variant)
Set out = CreateObject("System.Collections.Arraylist") ' a JavaScript-y array
For Each emlAddr In eml.Recipients
If Left(emlAddr.Address, 1) = "/" Then
' it's an Exchange email address... resolve it to an SMTP email address
out.Add ResolveDisplayNameToSMTP(emlAddr)
Else
out.Add emlAddr.Address
End If
Next
getRecepientEmailAddres = Join(out.ToArray(), ";")
End Function
Function ResolveDisplayNameToSMTP(sFromName) As String
' takes a Display Name (i.e. "James Smith") and turns it into an email address (james.smith#myco.com)
' necessary because the Outlook address is a long, convoluted string when the email is going to someone in the organization.
' source: https://stackoverflow.com/questions/31161726/creating-a-check-names-button-in-excel
Dim OLApp As Object 'Outlook.Application
Dim oRecip As Object 'Outlook.Recipient
Dim oEU As Object 'Outlook.ExchangeUser
Dim oEDL As Object 'Outlook.ExchangeDistributionList
Set OLApp = CreateObject("Outlook.Application")
Set oRecip = OLApp.Session.CreateRecipient(sFromName)
oRecip.Resolve
If oRecip.Resolved Then
Select Case oRecip.AddressEntry.AddressEntryUserType
Case 0, 5 'olExchangeUserAddressEntry & olExchangeRemoteUserAddressEntry
Set oEU = oRecip.AddressEntry.GetExchangeUser
If Not (oEU Is Nothing) Then
ResolveDisplayNameToSMTP = oEU.PrimarySmtpAddress
End If
Case 10, 30 'olOutlookContactAddressEntry & 'olSmtpAddressEntry
Dim PR_SMTP_ADDRESS As String
PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"
ResolveDisplayNameToSMTP = oRecip.AddressEntry.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS)
End Select
End If
End Function
Sub Write_to_excel(str1 As String, str2 As String, str3 As String)
Dim xlApp As Object
Dim sourceWB As Workbook
Dim sourceWH As Worksheet
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.EnableEvents = False
End With
Set sourceWB = Workbooks.Open(strFile, False, False)
Set sourceWH = sourceWB.Worksheets("Sheet1")
sourceWB.Activate
With sourceWH
lastrow = .Cells(.rows.Count, "A").End(xlUp).Row
End With
sourceWH.Cells(lastrow + 1, 1) = str1
sourceWH.Cells(lastrow + 1, 2) = str2
sourceWH.Cells(lastrow + 1, 3) = str3
sourceWB.Save
sourceWB.Close
End Sub
Error message and corrected code
Regards,
Ramon
First of all, there is no need to create a new Application instance in the ResolveDisplayNameToSMTP method:
Set OLApp = CreateObject("Outlook.Application")
Instead, you can use the Application property available in the Outlook VBA editor out of the box.
Second, you need to use the following code to get the SMTP address from the AddressEntry object:
Dim PR_SMTP_ADDRESS As String
Set PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"
ResolveDisplayNameToSMTP = oRecip.AddressEntry.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS)
Instead of the following line:
ResolveDisplayNameToSMTP = oRecip.AddressEntry.Address
Read more about that in the How to get the SMTP Address of the Sender of a Mail Item using Outlook Object Model? article.

MsAccess form - empty records originally, but needed to be filled mandatory, once the data entry started

I have MsAccess Form:
ClientName, ID fields - records filled with the information
Gender, Race, PrimaryLanguage fields (combo box type) are empty records
Users will fill Gender, Race and PrimaryLanguage, PrimaryDisability fields with the information.
My goal is - before user will move to the next record, I want he to be unable to proceed until those fields (Gender / Race) are filled with its content.
The problem is - Gender / Race / PrimaryLanguage, PrimaryDisability for the existing clients have to stay empty, but at the same time - when user starts filling it, it needs to be filled mandatory.
It works this way only in case if I am adding a new record.
(I have Gender / Race fields as required) - but doesn't work with the existing records.
PS - the answer provided below is great, but worked on my end for 2 fields only
What about 3 or more fields?
I had idea of adding the event procedure to each button in the Form, not to
the whole Form.
code should be something like:
Private Sub Gender_BeforeUpdate(Cancel As Integer)
If Nz(Me.Gender, "") = "" And (Nz(Me.Race, "") <> ""
Or (Nz(Me. PrimaryLanguage, "") <> ""
Or (Nz(Me. PrimaryDisability, "") <> "")
Then
MsgBox "Select Gender", vbInformation
Cancel = True
End If
End Sub
But it says about syntax mistakes
Please help!
Use BeforeUpdate event to cancel updating of a record before moving to another record
Private Sub Form_BeforeUpdate(Cancel As Integer)
If Nz(Me.ClientName, "") <> "" And Nz(Me.Gender, "") = "" And Nz(Me.Race, "") = "" And Nz(Me.PrimaryLanguage, "") = "" And Nz(Me.PrimaryDisability, "") = "" Then
Exit Sub
End If
If Nz(Me.Gender, "") = "" Then
MsgBox "Select Gender", vbInformation
Cancel = True
Exit Sub
End If
If Nz(Me.Race, "") = "" Then
MsgBox "Select Race", vbInformation
Cancel = True
Exit Sub
End If
If Nz(Me.PrimaryLanguage, "") = "" Then
MsgBox "Enter PrimaryLanguage", vbInformation
Cancel = True
Exit Sub
End If
If Nz(Me.PrimaryDisability, "") = "" Then
MsgBox "Enter PrimaryDisability ", vbInformation
Cancel = True
Exit Sub
End If
End Sub

Attaching access form and subform data in mail body

Thanks in advance :), I am trying to attach the data of subform also in mail body.
Current Status: I am able to attach Main forms data and generate mail but unable to attach subform's data as it only includes the first row, Tryied doing it through Subform and query both but no success. I will prefer to do it by subform itself. Subform's Name is : "subUpdateOrder". VB Code:
Private Sub InformCustomer_Click()
On Error GoTo Err_InformCustomer_Click
Dim CustName As String ' Customer Name
Dim varTo As Variant '-- Address for SendObject
Dim stText As String '-- E-mail text
Dim DelDate As Variant '-- Rec date for e-mail text
Dim stSubject As String '-- Subject line of e-mail
Dim stOrderID As String '-- The Order ID from form
Dim detailQry As String
'Dim stHelpDesk As String '-- Person who assigned ticket
'Dim strSQL As String '-- Create SQL update statement
'Dim errLoop As Error
CstName = Me![CustName]
varTo = Me![CustEmail]
stSubject = ":: Update - Oder Status ::"
stOrderID = Me.[OdrID]
DelDate = Me.[OdrDeliveryDate]
stText = "Dear" & CstName & _
"You have been assigned a new ticket." & Chr$(13) & Chr$(13) & _
"Order Number: " & stOrderID & Chr$(13) & _
"Please refer to your order status " & Chr$(13) & _
"Exp Delevery Date: " & DelDate & Chr$(13) & Chr$(13) & _
dQuery & Chr$(13) & _
"This is an automated message. Please do not respond to this e-mail."
'Write the e-mail content for sending to assignee
DoCmd.SendObject , , acFormatTXT, varTo, , , stSubject, stText, True
Err_InformCustomer_Click:
MsgBox Err.Description
End Sub
Form Img: Form and Command1 button to run the code
It would be something like (to insert before CstName = Me![CustName]):
Dim dQuery As String
Dim rs As DAO.Recordset
Set rs = Me!NameOfYourSubformCONTROL.Form.RecordsetClone
While Not rs.EOF
dQuery = dQuery & rs![Brand Name].Value & vbTab & rs![Model Name].Value & vbTab & rs![Color].Value & vbCrLF
Wend
Set rs = Nothing

Pass data between UserForms

Within Excel VBA I have a User Form similar to the following where the user enters an ID number and then the details are displayed on the user form:
Private Sub btnIDNo_Click()
Dim IDNo As Long
If txtIDNo.Text <> "" Then
If IsNumeric(txtIDNo.Text) = True Then
lblError.Caption = ""
IDNo = txtIDNo.Text
Worksheets("Details").Activate
Range("B4").Select
While ActiveCell.Value <> "" And ActiveCell.Value <> IDNo
ActiveCell.Offset(1, 0).Select
Wend
If ActiveCell.Value = IDNo Then
txtName.Value = ActiveCell.Offset(0, 1).Value
txtPhone.Value = ActiveCell.Offset(0, 2).Value
Else
lblError.Caption = "Cannot find ID nummber"
End If
Else
lblError.Caption = "Please enter the ID Number in numeric form"
End If
End If
End Sub
On the Details User Form, I have an "Edit" button. Clicking the "Edit" button would open another user form where the user can change the details of that ID number, but obviously not the ID number itself. To do this, I need to pass the ID number from the Details User Form to the Edit User Form. Is there a way of doing this?
The bottom on the Show Details User Form to open the Edit User Form is similar to the following:
Private Sub CommandButton1_Click()
Dim IDNo As Long
If txtIDNo.Text <> "" Then
If IsNumeric(txtIDNo.Text) = True Then
lblError.Caption = ""
IDNo= txtIDNo.Text
ufmEditDetails.Show
ufmShowDetails.Hide
Else
lblError.Caption = "Please enter the ID Number in numeric form"
End If
Range("B4").Select
End If
End Sub
I have already looked at the following links but they don't seem to help:
http://www.mrexcel.com/forum/excel-questions/671964-visual-basic-applications-pass-variables-between-user-forms.html
http://gregmaxey.mvps.org/word_tip_pages/userform_pass_data.html
http://peltiertech.com/Excel/PropertyProcedures.html
There are many many ways... Here are some...
Way 1
Declare a Public Variable in a Module
Assign to that variable in Userform1 and then launch Userform2. This variable will retain it's value. Example
In Userform1
Private Sub CommandButton1_Click()
MyVal = "Sid"
UserForm2.Show
End Sub
In Userform2
Private Sub CommandButton1_Click()
MsgBox MyVal
End Sub
In Module
Public MyVal
Way 2
Use the .Tag property of the userform
In Userform1
Private Sub CommandButton1_Click()
UserForm2.Tag = "Sid"
UserForm2.Show
End Sub
In Userform2
Private Sub CommandButton1_Click()
MsgBox Me.Tag
End Sub
Way 3
Add a Label in Userform2 and set it's visible property to False
In Userform1
Private Sub CommandButton1_Click()
UserForm2.Label1.Caption = "Sid"
UserForm2.Show
End Sub
In Userform2
Private Sub CommandButton1_Click()
MsgBox Label1.Caption
End Sub
There are serveral ways to solve this problem.
The one that I use is declare global or public variable in module
Example:
Public commonVariable As String
then in userform you can assign or retrieve value from this variable.
For example
in userform1:
Private Sub btnIDNo_Click()
commonVariable = "UserId"
End Sub
in UserForm2:
Private Sub CommandButton1_Click()
me.txtIDNo.Text = commonVariable
End Sub
The most simplest way is:
UserForm2.TxtIDNo.Text = UserForm1.txtIDNo.Text

File attachment using SMTP in VB6

I am writing an VB6 application in which I'm making use of cdosys.dll in order to send mails. I am able to attach and send the mails but the problem that I'm facing is the attached file icon image is not getting displayed correctly (default icon image is getting displayed). Also I am not able to attach the files between two paragraphs in the body part. I am using IBM Lotus Notes mail system. Please find below the code that I'm using and also the screenshot of issue that I'm facing
Set objEmail = CreateObject("CDO.Message")
objEmail.MimeFormatted = True
objEmail.To = to address
objEmail.From = from address
objEmail.Subject = "Additional Replacement Letters : " & Format(Now, "mm/dd")
objEmail.TextBody = "Hello Team," & vbCrLf & vbCrLf & "find below the attached letters"
Set fld = FSO.GetFolder(path)
For Each fil In fld.Files
Set iBp = objEmail.AddAttachment(fil)
Next
objEmail.TextBody = "Revert to me for any concerns"
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.domain.com"
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmail.Configuration.Fields.Update
objEmail.Send
Please help me how to solve this issue.
First, for the icons of files appearing in the attachments section. If a generic file icon is displayed, it may be because either:
your system doesn't have any/the correct MIME type defined for *.doc files (shouldn't be the case if you have Word installed);
the client cannot match any extension (and thus an icon) to the MIME type included with an attached file; or
if the recipient is viewing the emails through a web-based email system, the provider might not have/provide an image to show as an icon for those types of files.
In most cases it's the client software that is too lazy to display the appropriate icon.
Now, if you want the files to appear amid the email body, this is another story. Here an overview of what needs to be done:
First, you don't add files through IMessage.AddAttachment() but with IMessage.AddRelatedBodyPart();
When called, IMessage.AddRelatedBodyPart() will return an IBodyPart object;
Using the IBodyPart object, you need to assign a unique content ID to the piece – you can use the file name, but whatever the CID it must not contain spaces;
You then need to write your email body in HTML (so you can link to them);
In the message you'll add links to related parts as such:
Link to the file
where %CONTENT_ID_OF_THE_FILE% is the content ID you set for the file. Example:
Link to the file
There are two things you'll have to remember if you insert files this way:
You won't see any icon aside or elsewhere related to the file(s) attached, i.e. they'll appear as you set them through your HTML code. If you want any, you'll have to add images (not icon files) the same way and refer to them using the <img> tag and their content ID.
In many clients, you won't see the files in the attachments section, unless they're not being referred to in the body (or their content ID doesn't match, which is the same thing)
Here is some code. It's pretty complete, as I had to test it because I wasn't sure to remember everything correctly. Also, it is assumed you have among the references for your project Microsoft CDO for Windows 2000 Library and Microsoft Scripting Runtime.
Public Function SendNewLetters(ByVal PathForLetters As String, ByVal FromName As String, ByVal FromEmail As String, ByVal ToName As String, _
ByVal ToEmail As String, ByVal SMTPServer As String, ByVal SMTPPort As Long, ByVal SMTPUser As String, _
ByVal SMTPPassword As String, Optional ByVal UseSSL As Boolean = False, Optional ByRef ErrorCode As Long = 0, _
Optional ErrorDesc As String = vbNullString) As Boolean
On Error GoTo ErrorHandler
Const CdoReferenceTypeName = 1
Dim iMsg As CDO.Message ' Not using CreateObject() because I have the reference added
Dim sFileCID As String, sFileExt As String
Dim sIconImageSrc As String, sIconImageCID As String
Dim iBpAttachment As CDO.IBodyPart ' Will be reused more than once
Dim iBpIconImage As CDO.IBodyPart
Dim oFSO As Scripting.FileSystemObject
Dim oFolder As Scripting.Folder
Dim oFile As Scripting.File
Dim oDictAddedExtIcons As Scripting.Dictionary
Set iMsg = New CDO.Message
' Configure SMTP parameters
With iMsg.Configuration
.Fields(cdoSMTPServer) = SMTPServer
.Fields(cdoSMTPServerPort) = SMTPPort
.Fields(cdoSMTPUseSSL) = UseSSL
.Fields(cdoSMTPAuthenticate) = cdoBasic
.Fields(cdoSendUserName) = SMTPUser
.Fields(cdoSendPassword) = SMTPPassword
.Fields(cdoSMTPConnectionTimeout) = 60
.Fields(cdoSendUsingMethod) = cdoSendUsingPort
.Fields.Update
End With
' Set From and To fields
If Len(FromName) > 0 Then
' Let's say we already QP-encoded any special chars for the name
' and checked the email address
iMsg.From = FromName & " <" & FromEmail & ">"
Else
iMsg.From = FromEmail
End If
If Len(ToName) > 0 Then
' Same thing here
iMsg.To = ToName & " <" & ToEmail & ">"
Else
iMsg.To = ToEmail
End If
' Set subject (would need QP encoding as well)
iMsg.Subject = "Additional Replacement Letters : " & Format(Now, "mm/dd")
' Build the body
iMsg.HTMLBody = "<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional //EN""><html><body><p>Hello Team,<br/><br/>" & _
"Please find below the attached letters</p><div style=""display: table"">"
' Will be used to make sure icon images are only added once
Set oDictAddedExtIcons = New Scripting.Dictionary
' Add files here, one new body part for each
Set oFSO = New Scripting.FileSystemObject
If oFSO.FolderExists(PathForLetters) Then
Set oFolder = oFSO.GetFolder(PathForLetters)
For Each oFile In oFolder.Files
' IMPORTANT: Content-IDs should not contain spaces
sFileCID = Replace$(oFile.Name, " ", "_")
Set iBpAttachment = iMsg.AddRelatedBodyPart(oFile.Path, oFile.Name, CdoReferenceTypeName)
iBpAttachment.Fields.Item("urn:schemas:mailheader:content-id") = "<" & sFileCID & ">"
iBpAttachment.Fields.Update ' Dont' forget that line
sFileExt = LCase$(GetFileExtension(oFile.Name))
sIconImageSrc = vbNullString
Select Case sFileExt
Case "doc"
' We provide here the path to a 32x32 image of the doc file icon
sIconImageSrc = "C:\Users\MyUserName\Desktop\DocIcon.png"
' We could also provide images for other extensions, or
' (more involved) query the DefaultIcon for any extension from
' the registry, load the icon from the ico/exe/dll file and
' find the best size/resize if necessary (already have the
' code, but it's a *lot* of code).
Case ".."
' Add support for more
End Select
If Len(sIconImageSrc) > 0 Then
If Not oDictAddedExtIcons.Exists(sFileExt) Then
sIconImageCID = GetFilePart(sIconImageSrc) ' Is the filename for this and the next line
Set iBpIconImage = iMsg.AddRelatedBodyPart(sIconImageSrc, sIconImageCID, CdoReferenceTypeName)
' IMPORTANT: Content-IDs should not contain spaces
sIconImageCID = Replace$(sIconImageCID, " ", "_")
iBpIconImage.Fields.Item("urn:schemas:mailheader:content-id") = "<" & sIconImageCID & ">"
iBpIconImage.Fields.Update ' Dont' forget that line
oDictAddedExtIcons.Add sFileExt, sIconImageCID
sIconImageSrc = "cid:" & sIconImageCID
Else
sIconImageSrc = "cid:" & oDictAddedExtIcons.Item(sFileExt)
End If
End If
iMsg.HTMLBody = iMsg.HTMLBody & "<div style=""display: table-row""><div style=""text-align: left; " & _
"vertical-align: middle; margin-right: 10px;"">"
If Len(sIconImageSrc) > 0 Then
iMsg.HTMLBody = iMsg.HTMLBody & "<img src=""" & sIconImageSrc & """ border=""0"" />"
Else
iMsg.HTMLBody = iMsg.HTMLBody & " "
End If
iMsg.HTMLBody = iMsg.HTMLBody & "</div><div style=""display: table-cell; text-align: left; vertical-align: middle;"">"
iMsg.HTMLBody = iMsg.HTMLBody & "" & oFile.Name & ""
iMsg.HTMLBody = iMsg.HTMLBody & "</div></div>"
Next
End If
iMsg.HTMLBody = iMsg.HTMLBody & "</div><br/>"
iMsg.HTMLBody = iMsg.HTMLBody & "<p>Revert to me for any concerns.</p></body></html>"
' Send away!
iMsg.Send
SendNewLetters = True
Exit Function
ErrorHandler:
ErrorCode = Err.Number
ErrorDesc = Err.Description
SendNewLetters = False
End Function
Public Function GetFilePart(ByVal FilePath As String) As String
Dim lPos As Long
lPos = InStrRev(FilePath, "\")
If lPos > 0 Then
GetFilePart = Right$(FilePath, Len(FilePath) - lPos)
End If
End Function
Public Function GetFileExtension(ByVal FilePath As String, Optional ByVal WithDot As Boolean = False) As String
Dim lPos As Long
lPos = InStrRev(FilePath, ".")
If InStr(1, FilePath, ".") Then
If WithDot Then
GetFileExtension = Right$(FilePath, Len(FilePath) - lPos + 1)
Else
GetFileExtension = Right$(FilePath, Len(FilePath) - lPos)
End If
End If
End Function
Here is the image I used for the *.doc icon:
And this is what it would look like when sent:
I hope it works for you!