I have read numerous responses that are close to what I am looking for, but each time it doesn't work in my code.
This should be a pretty basic question, but I am hoping someone can look at this and see my error quickly.
I am using Excel to create a Word Doc which is then saved on the users Desktop in a folder named with the current date.
Everything works perfectly, but now all I am trying to do is add to the Word doc the name of the string "IRN" which is a cell in the Excel worksheet.
I also need to attach the created Word doc to an Outlook message.
I will only include the intro and end of my code as the body should not matter.
Sub TDOutlook()
Dim TD As Word.Application
Dim Doc As Word.Document
Dim path As String
Dim filename As String
Dim StudentName As String
Dim StudentAddress1 As String
Dim City As String
Dim MrMrs As String
Dim StudentLast As String
Dim IRN As String
Dim CourseReq As String
Dim CourseName As String
Dim CourseStart As String
Dim Cost As String
Dim Deferred As String
Dim Graphic As String
Dim Footer1 As Word.Range
Dim Body As Word.Paragraph
Dim OutApp As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
path = Environ("USERPROFILE") & "\Desktop\" & Format(Now, "mm-dd-yyyy")
On Error Resume Next
MkDir path
On Error GoTo 0
'Outlook
Set OutApp = CreateObject("Outlook.Application")
Set objOutlookMsg = OutApp.CreateItem(olMailItem)
objOutlookMsg.SentOnBehalfOfName = "bbb#ppp.edu"
objOutlookMsg.Subject = "FinServ-TD"
objOutlookMsg.HTMLBody = "Testing this macro" & vbCrLf & vbCrLf
'Display Outlook
objOutlookMsg.Display
'Opens Word
Set TD = CreateObject("Word.Application")
'Displays the document
TD.Visible = False
'Add New Document
Set Doc = TD.Documents.Add
filename = path & "\TD" '& IRN
Doc.SaveAs filename
'Attach Word to Outlook
objOutlookMsg.Attachments.Add Doc.filename <----This is broken
Doc.Close
TD.Quit
'Application.ScreenUpdating = True
End Sub
Everything works perfectly, but now all I am trying to do is add to the Word doc the name of the string "IRN" which is a cell in the Excel worksheet.
To get the Cell Value Try this
FileName = Path & "\TD" & Sheets("Sheet1").Range("A1").Text & ".docx"
I also need to attach the created Word doc to an Outlook message.
To attached saved file, change this
objOutlookMsg.Attachments.Add Doc.filename To this
ObjOutlookMsg.Attachments.Add (FileName)
Related
I am trying to save a list of email in msg format to htm format so that Xceptor tool can read the email as pdf. (Without a vba, Currently I manually open the email in Outlook and save as htm one by one.)
I found below script but I get
"Run Time error 287: Application-defined or object-defined error".
Sub SaveMSG_as_HTML()
Dim olMsg As MailItem
Dim strPath As String
Dim strMsg As String
Dim strHTML As String
strPath = "\\Hbap.adroot.hsbc\hk\Finance\224017\AMH_A2R_2\WRK\AAC\PL\To GFC\Movement Table\MvtXceptor\Configuration\Table18.1\"
strMsg = "RE CRR Inquiry as atJan-00-00 - --.msg"
strHTML = Left(strMsg, InStrRev(strMsg, Chr(46))) & "html"
Set olMsg = Session.OpenSharedItem(strPath & strMsg)
olMsg.SaveAs Path:=strPath & strHTML, Type:=olHTML
olMsg.Close olDiscard
lbl_Exit:
Set olMsg = Nothing
Exit Sub
End Sub
Without a vba, i need to open the email in outlook and save as htm one by one.
Without VBA? So I guess you want to use VBScript? Say, directly run it from desktop by clicking on the .vbs file? If yes, then you need to declare and create/get the outlook object before you can work with it. Otherwise how will your code know what is Session? Also olHTML and olDiscard are Outlook constants. VbScript will not know what they are.
Is this what you are trying? Paste this in Notepad and save it as Sample.Vbs
Private Const olHTML = 5
Private Const olDiscard = 1
Dim OutApp
Dim olMsg
Dim nsOutlook
Dim strPath
Dim strMsg
Dim strHTML
'~~> I used these values for testing. Change as applicable
strPath = "C:\Temp\"
strMsg = "test.msg"
strHTML = "test.html"
Set OutApp = CreateObject("Outlook.Application")
Set nsOutlook = OutApp.GetNamespace("MAPI")
Set olMsg = nsOutlook.OpenSharedItem(strPath & strMsg)
olMsg.SaveAs strPath & strHTML, olHTML
olMsg.Close olDiscard
Set olMsg = Nothing
Set nsOutlook = Nothing
Set OutApp = Nothing
The following code does everything I want: pulls email, saves attachments, extracts files
EXCEPT save the original email to the folder fDest. I seem unable to see the solution.
This seems to be the problematic line as it won't save the email:
"mi.SaveAs fDest2, olMSG"
Sub SaveAttachments()
Dim ol As Outlook.Application
Dim ns As Outlook.Namespace
Dim fol As Outlook.Folder
Dim i As Object
Dim mi As Outlook.MailItem
Dim at As Outlook.Attachment
Dim Inbox As MAPIFolder
Dim strDate As String
Dim oApp As Object
Dim fDest As Variant
Dim j As Variant
Dim sh As String
Dim FileDialog As FileDialog
Dim Tracker As Workbook
Dim fSheet As Sheets
Dim LastRow As Long
Dim strFilePath
Dim fTracker As Workbook
strDate = InputBox("Enter Date in format dd-Mmm-yyyy", "User Date", Format(Now(), "dd-Mmm-yyyy"))
strFilePath = "\\namdfs\CARDS\MWD\GROUPS\GCM_NAM\2021\05 May\"
fTrackerName = "Inquiry.Tracker.SWPA.Violations.May.2021.xlsx" '
On Error Resume Next
Set fTracker = Workbooks(fTrackerName)
'If Err Then Set fTracker = Workbooks.Open(strFilePath & fTrackerName)
On Error GoTo 0
'Windows(fTrackerName).Activate
Set ol = New Outlook.Application
Set ns = ol.GetNamespace("MAPI")
Set fol = ns.Folders("GCMNamLogs").Folders("Inbox")
fDest = "C:\Users\jb76991\Desktop\Violations_Emails\"
fUser = UCase(Environ("username")) & ":" & Chr(10) & Now()
For Each i In fol.Items.Restrict("#SQL=urn:schemas:httpmail:subject LIKE '%" & strDate & "%'")
'Debug.Print fDest & i & ".msg"
If i.Class = olMail Then
Set mi = i
fDest2 = fDest & mi.Subject & ".msg"
mi.SaveAs fDest2, olMSG
For Each at In mi.Attachments
'do something with attachments but i've commented it out
Next at
End If
Next i
MsgBox ("Completed")
End Sub
Can anyone tell me how to save the original emails that are being filtered?
You must be sure there are no invalid characters in the filename. See What characters are forbidden in Windows and Linux directory names? for more information. So, I'd suggest using the Replace method available in VBA before passing anything to the SaveAs method.
Another point is that you need to specify unique file names to each email. Make sure the generated file name is unique for a folder.
I have created a fully functional outlook macro, that downloads Outlook attachments to OneDrive specified folder.
So the macro would update the file name with the email domain and month/year
e.g.
from original attachment name "Invoice_GBR_Z-GRX_2019_07.pdf"
it becomes "comfone.com_08-2019___Invoice_GBR_Z-GRX_2019_07.pdf" after executing the macro.
However, I would like the macro to also have the ability to compare against a static Excel table called Table.xls on my desktop (2 columns where column A contain the email domain name, and column B containing its respective company code), wherein if the Excel cell contains "comfone.com", then its corresponding company code say 0001 would then be appended to the file name
So the file name gets updated to
"0001_comfone.com_08-2019___Invoice_GBR_Z-GRX_2019_07.pdf"
I'm struggling quite a fair bit not knowing how to reference to an Excel table from my Outlook vba.
Public Sub SaveAttachments()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem 'Object
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String
Dim saveName As String
Dim userName As String
Dim sndrEmailAdd As String
Dim sndrEmailRight As String
Dim sndrEmailPreDot As String
' Get the path to your OneDrive folder.
userName = CreateObject("WScript.Network").userName
Debug.Print userName
'strFolderpath = "C:\Users\" & VBA.Environ$("USERNAME") & "\OneDrive - SAP
SE"
strFolderpath = "C:\Users\" & userName & "\OneDrive - SAP SE"
On Error Resume Next
' Instantiate an Outlook Application object.
Set objOL = CreateObject("Outlook.Application")
' Get the collection of selected objects.
Set objSelection = objOL.ActiveExplorer.Selection
' Set the Test folder, change "Test" to any folder name in your OneDrive
strFolderpath = strFolderpath & "\Downloaded Invoices\"
' Check each selected item for attachments. If attachments exist,
' save them to the strFolderPath folder and strip them from the item.
For Each objMsg In objSelection
' This code only strips attachments from mail items.
' If objMsg.class=olMail Then
' Get the Attachments collection of the item.
Set objAttachments = objMsg.Attachments
lngCount = objAttachments.Count
strDeletedFiles = ""
If lngCount > 0 Then
' We need to use a count down loop for removing items
' from a collection. Otherwise, the loop counter gets
' confused and only every other item is removed.
For i = lngCount To 1 Step -1
'Extract text, after # and before dot, from the email address.
sndrEmailAdd = objMsg.SenderEmailAddress
Debug.Print sndrEmailAdd
'Debug.Print " position of # sign: " & InStr(sndrEmailAdd, "#")
'Debug.Print " number of characters right of # sign: " &
Len(sndrEmailAdd) - InStr(sndrEmailAdd, "#")
'sndrEmailRight = Right(sndrEmailAdd, Len(sndrEmailAdd) -
InStr(sndrEmailAdd, "#"))
sndrEmailRight = Right(sndrEmailAdd, Len(sndrEmailAdd) -
InStr(sndrEmailAdd, "#"))
Debug.Print " text after # sign: " & sndrEmailRight
Debug.Print " position of the (first) . period in the remaining text:
" & InStr(sndrEmailRight, ".")
'sndrEmailPreDot = Left(sndrEmailRight, InStr(sndrEmailRight, ".") -
1)
' Save attachment before deleting from item.
' Get the file name.
strFile = sndrEmailRight & "_" & Format(DateAdd("m", -1,
objMsg.ReceivedTime), "mm-yyyy") & "___" &
objAttachments.item(i).FileName
' Combine with the path to the Temp folder.
saveName = strFolderpath & strFile
' Save the attachment as a file.
objAttachments.item(i).SaveAsFile saveName
' Delete the attachment.
'objAttachments.item(i).Delete
Next i
objMsg.Save
End If
Next
ExitSub:
Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub
See example on how to call Excel from Outlook
https://stackoverflow.com/a/41801050/4539709
I have updated your code, make sure to Reference to Microsoft Excel xx.x Object Library and update your one-drive folder path
Your code example
Option Explicit
Public Sub SaveAttachments()
Dim Atmts As Outlook.Attachments
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strDeletedFiles As String
Dim saveName As String
Dim userName As String
Dim sndrEmailAdd As String
Dim sndrEmailRight As String
Dim sndrEmailPreDot As String
Dim strFolderpath As String
strFolderpath = "C:\Temp\"
' Get the collection of selected objects.
Dim objSelection As Outlook.Selection
Set objSelection = Application.ActiveExplorer.Selection
Dim xlApp As Excel.Application
Set xlApp = New Excel.Application
Dim Book As Workbook
Set Book = xlApp.Workbooks.Open("C:\Temp\Book1.xlsx")
Dim xlStarted As Boolean
xlStarted = True
Dim Sht As Excel.Worksheet
Set Sht = Book.Sheets("Sheet1")
Dim Rng As Range
' Check each selected item for attachments. If attachments exist,
' save them to the strFolderPath folder and strip them from the item.
Dim objMsg As Outlook.MailItem 'Object
For Each objMsg In objSelection
' This code only strips attachments from mail items.
' If objMsg.class=olMail Then
' Get the Attachments collection of the item.
Set Atmts = objMsg.Attachments
lngCount = Atmts.Count
Debug.Print lngCount
strDeletedFiles = ""
If lngCount > 0 Then
' We need to use a count down loop for removing items
' from a collection. Otherwise, the loop counter gets
' confused and only every other item is removed.
For i = lngCount To 1 Step -1
'Extract text, after # and before dot, from the email address.
sndrEmailAdd = objMsg.SenderEmailAddress
Debug.Print sndrEmailAdd
sndrEmailRight = Right(sndrEmailAdd, Len( _
sndrEmailAdd) - InStr( _
sndrEmailAdd, "#"))
Debug.Print sndrEmailRight
sndrEmailPreDot = Left(sndrEmailRight, _
InStr(sndrEmailRight, ".") - 1)
Debug.Print sndrEmailPreDot
For Each Rng In Sht.Range("A1", Sht.Range("A100").End(xlUp))
If (Rng.Value) = sndrEmailRight Then
sndrEmailPreDot = Rng.Offset(0, 1).Value & "_" & sndrEmailPreDot
Debug.Print sndrEmailPreDot
End If
Next
' Save attachment before deleting from item.
' Get the file name.
strFile = sndrEmailPreDot & "_" & _
Format(DateAdd("m", -1, objMsg.ReceivedTime _
), "mm-yyyy") & "___" & Atmts.Item(i).FileName
Debug.Print strFile
' Combine with the path to the Temp folder.
saveName = strFolderpath & strFile
Debug.Print saveName
' Save the attachment as a file.
Atmts.Item(i).SaveAsFile saveName
' Delete the attachment.
'Atmts.item(i).Delete
Next i
objMsg.Save
End If
Next
' Close & SaveChanges
Book.Close SaveChanges:=True
If xlStarted Then
xlApp.Quit
End If
Set xlApp = Nothing
Set Book = Nothing
Set Sht = Nothing
Set Rng = Nothing
Set Atmts = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
End Sub
I am trying to save all the emails, resulting out of instant text search into the hard drive folder. the below code is able to perform the search but giving me an error at selectallitems line while selecting each mail and saving them in HD. code is in excel vba;
Dim OlApp As Outlook.Application
Set OlApp = CreateObject("Outlook.Application")
Dim fldrpath As String
fldrpath = "\\mydata\EMAILS\
Check subfolder for messages and exit of none found
txtsearch = "abc#xyz.com, received:4/1/2017..4/30/2017"
OlApp.ActiveExplorer.Search txtsearch, olSearchScopeAllFolders
Dim myitem As Outlook.MailItem
Dim objitem As Object
Set myitem = OlApp.ActiveExplorer.SelectAllItems
Set objitem = myitem
objitem.SaveAs fldrpath & "test" & ".msg", olMSG
Any other alternative code to get the emails saved will also be appreciated.
Thanks in advance !! looking for a quick solution
Saving search results appears to be more easily achieved a different way.
From Outlook, not Excel.
Sub SearchForStr_Save()
Dim strSearch As String
Dim strDASLFilter As String
Dim strScope As String
Dim objItem As Object
Dim objSearch As search
Dim srchFolder As folder
Dim fldrpath As String
strSearch = "abc#xyz.com"
strDASLFilter = "urn:schemas:httpmail:textdescription LIKE '%" & strSearch & "%'"
strScope = "'Inbox'"
Set objSearch = AdvancedSearch(Scope:=strScope, filter:=strDASLFilter, SearchSubFolders:=True, Tag:="SearchFolder")
Set srchFolder = objSearch.Save(strSearch)
'fldrpath = "\\mydata\EMAILS\"
fldrpath = "h:\test\"
For Each objItem In srchFolder.Items
'Debug.Print objItem.subject
If objItem.Class = olMail Then
objItem.SaveAs fldrpath & "test" & ".msg", olMsg
End If
Next
ExitRoutine:
Set objSearch = Nothing
Set srchFolder = Nothing
End Sub
We use Outlook 2010 and receive emails with Excel attachments. We manually save the attachment in a sub-folder that we create within a divisional folder on a network drive.
What I'm curious about is if it's possible to
Use code to check incoming emails to see if they have an attachment,
Then check the attachment to see if it's an .XLSX,
If so, open the attachment, check the value of a particular cell,
then store the account name and account number as a string and a variable
then use those to create the sub-folders in the appropriate Windows directory.
** I forgot to post what I had done so far. I believe Brett answered my ??, but maybe someone else would be able to use snippets of it.
Private Sub cmdConnectToOutlook_Click()
Dim appOutlook As Outlook.Application
Dim ns As Outlook.Namespace
Dim inbox As Outlook.MAPIFolder
Dim item As Object
Dim atmt As Outlook.Attachment
Dim filename As String
Dim i As Integer
Set appOutlook = GetObject(, "Outlook.Application")
Set ns = appOutlook.GetNamespace("MAPI")
Set inbox = ns.GetDefaultFolder(olFolderInbox)
i = 0
If inbox.Items.Count = 0 Then
MsgBox "There are no messages in the Inbox.", vbInformation, _
"Nothing Found"
Exit Sub
End If
For Each item In inbox.Items
For Each atmt In item.Attachments
If Right(atmt.filename, 4) = "xlsx" Then
filename = "\\temp\" & atmt.filename
atmt.SaveAsFile filename
i = i + 1
End If
Next atmt
Next item
MsgBox "Attachments have been saved.", vbInformation, "Finished"
Set atmt = Nothing
Set item = Nothing
Set ns = Nothing
End Sub
Having said it is lengthy here is one way to do it. My code from VBA Code to save an attachment (excel file) from an Outlook email that was inside another email as an attachment may also be of interest
You will need to update your file path, and the cell range from the file that you are opening
In my testing I sent a message to myself with a pdf file and an excel workbook with "bob" in the A1 in the first sheet
The code below found the excel file, saved it, opened it, create a directory c:\temp\bob then killed the saved file
Private Sub Application_NewMailEx _
(ByVal EntryIDCollection As String)
'Uses the new mail techniquer from http://www.outlookcode.com/article.aspx?id=62
Dim arr() As String
Dim lngCnt As Long
Dim olAtt As Attachment
Dim strFolder As String
Dim strFileName As String
Dim strNewFolder
Dim olns As Outlook.NameSpace
Dim olItem As MailItem
Dim objExcel As Object
Dim objWB As Object
'Open Excel in the background
Set objExcel = CreateObject("excel.application")
'Set working folder
strFolder = "c:\temp"
On Error Resume Next
Set olns = Application.Session
arr = Split(EntryIDCollection, ",")
On Error GoTo 0
For lngCnt = 0 To UBound(arr)
Set olItem = olns.GetItemFromID(arr(lngCnt))
'Check new item is a mail message
If olItem.Class = olMail Then
'Force code to count attachments
DoEvents
For Each olAtt In olItem.Attachments
'Check attachments have at least 5 characters before matching a ".xlsx" string
If Len(olAtt.FileName) >= 5 Then
If Right$(olAtt.FileName, 5) = ".xlsx" Then
strFileName = strFolder & "\" & olAtt.FileName
'Save xl attachemnt to working folder
olAtt.SaveAsFile strFileName
On Error Resume Next
'Open excel workbook and make a sub directory in the working folder with the value from A1 of the first sheet
Set objWB = objExcel.Workbooks.Open(strFileName)
MkDir strFolder & "\" & objWB.sheets(1).Range("A1")
'Close the xl file
objWB.Close False
'Delete the saved attachment
Kill strFileName
On Error Goto 0
End If
End If
Next
End If
Next
'tidy up
Set olns = Nothing
Set olItem = Nothing
objExcel.Quit
Set objExcel = Nothing
End Sub