Count Outlook VBA attachment - vba

Can you help me to improve the below VBA code to be able to correctly count e-mails + attachments form a selected range (outlook 2010)
Sub CountAttachmentsMulti()
Set mySelect = Outlook.ActiveExplorer.Selection
For Each Item In mySelect
j = Item.Attachments.Count + j
i = i + 1
Next Item
MsgBox "Selected " & i & " messages with " & j & " attachements"
End Sub
That is the code the problem is that counts also as attachments the picture in the signatures and give a wrong count meaning more attachments then the actually are
Can you help to amend the code to bypass from counting the images in signatures
BR
Gabi

Try this
Sub CountAttachmentsValid()
Dim olkItem As Outlook.mailitem
Dim olkAttachment As Outlook.attachment
Dim strFilename As String
Dim strExtension As String
Dim lngExtIndex As Long
Dim strBaseFilename As String
Dim cnt As Long
Dim mySelect As Selection
Dim iExt As Long
Dim validExtString As String
Dim validExtArray() As String
validExtString = ".doc .docx .xls .xlsx .msg .pdf .txt" ' <---- Update as needed
validExtArray = Split(validExtString, " ")
Set mySelect = Outlook.ActiveExplorer.Selection
For Each olkItem In mySelect
For Each olkAttachment In olkItem.Attachments
On Error GoTo cannotPerformOperation
strFilename = olkAttachment.FileName
lngExtIndex = InStrRev(strFilename, ".")
strBaseFilename = Left(strFilename, lngExtIndex - 1)
strExtension = Mid(strFilename, lngExtIndex)
For iExt = 0 To UBound(validExtArray)
If LCase(strExtension) = LCase(validExtArray(iExt)) Then
cnt = cnt + 1
Exit For
End If
Next iExt
skipped:
Next olkAttachment
Next olkItem
GoTo exiting
cannotPerformOperation:
'Debug.Print " ** " & olkAttachment.DisplayName & " not counted"
Resume skipped
exiting:
MsgBox "Selected " & mySelect.count & " messages with " & cnt & " recognized attachments"
End Sub

Related

Open method not working to open ppts from a ppt

I'm having a bit of trouble here. My code stops with a Run-time error -2147467259 (80004005) Mehod 'Open' of object 'Presentations: failed.
This code presents a warning, prompts for source and target folder and loops through all files in the source folder, opening each file and exporting each slide as an individual file, and again until the last file in the folder.
I put a couple of msgboxes to see if it was a problem with the names, re-wrote the open file segment based on some code from MVP Andy Pope, yet nothing.
Any help is deeply appreciated.
Sub ExportIndividualSlides()
''Application.DisplayAlerts = False
Dim ObjPPAPP As New PowerPoint.Application
Dim objPPPres As PowerPoint.Presentation
Dim objPPSlide As PowerPoint.Slide
'Initial directory path.
Dim SourceFolder As String
Dim TargetFolder As String
SourceFolder = "c:\source"
TargetFolder = "c:\target"
Dim Slide As Long
Dim SourcePresentation As Presentation
Dim SourcePresentationName As String
Dim TargetFileName As String
Dim SourceNamePath
Debug.Print "-- Start --------------------------------"
ActiveWindow.ViewType = ppViewNormal
'Loop through ppt* files only in source folder
SourcePresentationName = Dir(SourceFolder & "\*.ppt*")
MsgBox "SPN:" & SourcePresentationName
While (SourcePresentationName <> "")
SourceNamePath = SourceFolder & "\" & SourcePresentationName
Debug.Print " SourceNamePath"
MsgBox SourceNamePath
Set ObjPPAPP = New PowerPoint.Application
ObjPPAPP.Visible = True
Set objPPPres = ObjPPAPP.Presentations.Open(SourceNamePath)
' On Error GoTo errorhandler
' Open source files
Set SourcePresentation = Presentations.Open(FileName:=SourcePresentationName, WithWindow:=False)
Debug.Print " SourcePresentation: " & SourcePresentation.Name
' Loop through slides
For Slide = 1 To SourcePresentation.Slides.Count
Debug.Print " Slide: " & Slide
' Create a unique filename and save a copy of each slide
TargetFileName = Left(SourcePresentation.Name, InStrRev(SourcePresentation.Name, ".") - 1) & " [" & Slide & "].pptx"
TargetNamePath = TargetFolder & "\" & TargetFileName
Debug.Print " TargetNamePath: " & TargetNamePath
SourcePresentation.Slides(Slide).Export TargetNamePath, "PPTX"
Next Slide
objPPPres = Nothing
SourcePresentation.Close
SourcePresentationName = Dir
Wend
On Error GoTo 0
Exit Sub
errorhandler:
Debug.Print Err, Err.Description
Resume Next
End Sub
This worked for me:
Sub ExportIndividualSlides()
'use const for fixed values
Const SOURCE_FOLDER As String = "c:\source\" 'include terminal \
Const TARGET_FOLDER As String = "c:\target\"
Dim objPres As PowerPoint.Presentation
Dim Slide As Long
Dim SourcePresentationName As String
Dim TargetFileName As String
Dim TargetNamePath As String
Dim SourceNamePath
Debug.Print "-- Start --------------------------------"
ActiveWindow.ViewType = ppViewNormal
On Error GoTo errorhandler
'Loop through ppt* files only in source folder
SourcePresentationName = Dir(SOURCE_FOLDER & "*.ppt*")
Do While Len(SourcePresentationName) > 0
SourceNamePath = SOURCE_FOLDER & SourcePresentationName
Debug.Print "Opening: " & SourceNamePath
Set objPres = Presentations.Open(SourceNamePath)
' Loop through slides
For Slide = 1 To objPres.Slides.Count
Debug.Print " Slide: " & Slide
' Create a unique filename and save a copy of each slide
TargetFileName = Left(objPres.Name, InStrRev(objPres.Name, ".") - 1) & " [" & Slide & "].pptx"
TargetNamePath = TARGET_FOLDER & TargetFileName
Debug.Print " TargetNamePath: " & TargetNamePath
objPres.Slides(Slide).Export TargetNamePath, "PPTX"
Next Slide
objPres.Close
SourcePresentationName = Dir() 'next file
Loop
Exit Sub
errorhandler:
Debug.Print Err, Err.Description
Resume Next
End Sub

Save PDF attachments only using If UCase + SaveAsFile + SenderEmailAddress

I have two VBA macros that are slightly different and I want to combine the best of both.
Both save attachments within a selection of emails, however:
Macro A saves every attachment within the selection as a PDF. Some are JPEG signatures or disclaimers etc. that I don't want. The plus side is that it uses eml.SenderEmailAddress which is super as I want the name of the saved attachment to include 'someone#something.com'
Macro B saves every attachment within the selection as a PDF but uses the If UCase function to filter out PDF files only. For instance if an email contains a .txt and .pdf file, only the PDF file is considered. I don't have to clean out fake pdfs.
I cannot figure out how to incorporate SenderEmailAddress into this macro.
How do I merge the features in bold above?
Macro A)
Sub SaveAttachmentsFromSelectedItemsPDF()
Dim currentItem As Object
Dim currentAttachment As Attachment
Dim saveToFolder As String
Dim savedFileCountPDF As Long
saveToFolder = "the_path_private_its_a_work_one_lol"
savedFileCountPDF = 0
For Each currentItem In Application.ActiveExplorer.Selection
For Each currentAttachment In currentItem.Attachments
If UCase(Right(currentAttachment.DisplayName, 4)) = ".PDF" Then
currentAttachment.SaveAsFile saveToFolder & "\" & _
Left(currentAttachment.DisplayName, Len(currentAttachment.DisplayName) - 4) & "_" & Format(Now, "yyyy-mm-dd_hh-mm-ss") & ".pdf"
savedFileCountPDF = savedFileCountPDF + 1
End If
Next currentAttachment
Next currentItem
MsgBox "Number of PDF files saved: " & savedFileCountPDF, vbInformation
End Sub
Macro B)
Sub attsave_yann()
Dim win As Outlook.Explorer
Dim sel As Outlook.Selection
Dim att As Outlook.Attachments
Dim eml As MailItem
Dim i As Integer
Dim fn As String
Dim objAtt As Outlook.Attachment
Dim myRandom As Double
Randomize 'Initialize the Rnd function
myRandom = Rnd 'Generate a random number between 0-1
' Count = Count + 1
Set win = Application.ActiveExplorer
Set sel = win.Selection
For Each eml In sel
Set att = eml.Attachments
If UCase(Right(att.DisplayName, 4)) = ".PDF" Then
For i = 1 To att.Count
fn = "the_path_private_its_a_work_one_lol" & eml.SenderEmailAddress & "_" & Rnd & "_.pdf"
att(i).SaveAsFile fn
Next i
End If
Next
End Sub
B is almost there:
Sub attsave_yann()
Dim eml As MailItem
Dim fn As String
Dim objAtt As Outlook.Attachment
Randomize 'Initialize the Rnd function
For Each eml In Application.ActiveExplorer.Selection
For Each objAtt In eml.Attachments
'need to test objAtt.DisplayName
If UCase(objAtt.DisplayName) Like "*.PDF" Then
fn = "the_path_private_its_a_work_one_lol" & _
DomainOnly(eml.SenderEmailAddress) & "_" & Rnd & "_.pdf"
objAtt.SaveAsFile fn
End If
Next objAtt
Next
End Sub
'return only the part after the `#`
Function DomainOnly(sAddr as string)
Dim arr
arr = Split(sAddr, "#")
if UBound(arr) = 0 then
DomainOnly = sAddr
Else
DomainOnly = arr(1)
End If
End Function

Splitting Word document into multiple .txt files using a macro

I am splitting a single MS Word document into multiple using a custom delimiter. I am able to create multiple files in MS Word format, but I want to create multiple .txt files instead.
The code that I am using now is:
Sub SplitNotes(delim As String, strFilename As String)
Dim doc As Document
Dim arrNotes
Dim I As Long
Dim X As Long
Dim Response As Integer
arrNotes = Split(ActiveDocument.Range, delim)
Response = MsgBox("This will split the document into " &
UBound(arrNotes) + 1 & " sections. Do you wish to proceed?", 4)
If Response = 7 Then Exit Sub
For I = LBound(arrNotes) To UBound(arrNotes)
If Trim(arrNotes(I)) <> "" Then
X = X + 1
Set doc = Documents.Add
doc.Range = arrNotes(I)
doc.SaveAs ThisDocument.Path & "\" & strFilename & Format(X, "000")
doc.Close True
End If
Next I
End Sub
Sub test()
' delimiter & filename
SplitNotes "%%%%%%%%%%%%%%", "Notes "
End Sub
Can anyone help me with this please?
Try this and see if it does what you want.
Sub SplitNotes(delim As String, strFilename As String)
Dim doc As Document
Dim arrNotes
Dim I As Long
Dim X As Long
Dim Response As Integer
arrNotes = Split(ActiveDocument.Range, delim)
Response = MsgBox("This will split the document into " & UBound(arrNotes) + 1 & " sections. Do you wish to proceed?", 4)
If Response = 7 Then Exit Sub
For I = LBound(arrNotes) To UBound(arrNotes)
If Trim(arrNotes(I)) <> "" Then
X = X + 1
Set doc = Documents.Add
doc.Range = arrNotes(I)
doc.SaveAs ThisDocument.Path & "\" & strFilename & ".txt"
doc.Close True
End If
Next I
End Sub
Sub test()
' delimiter & filename
SplitNotes "///", "Notes "
End Sub

Changing Outlook 2013 Email Subject Using VBA

I am using the code below to save multiple selected emails in a standard file naming format in a folder, who's path is selected from a text box (textbox1). Depending on whether a checkbox (checkbox1) is selected or not will determine whether the emails are deleted after running the code. If the the checkbox is not selected then the emails are saved to the folder but not deleted from Outlook. If the checkbox is not selected then I want the email subject in Outlook to be changed in order that I know that I have previously saved the email. The code below pretty much does everything I want except changing the email subject. If I select only one email all works fine. However if I select more than one email then only the subject of the first email gets changed. Any help appreciated.
Sub SaveIncoming()
Dim lngC As Long
Dim msgItem As Outlook.MailItem
Dim strPath As String
Dim FiledSubject As String
On Error Resume Next
strPath = UserForm1.TextBox1.Value
On Error GoTo 0
If strPath = "" Then Exit Sub
If Right(strPath, 1) <> "\" Then strPath = strPath & "\"
If TypeName(Application.ActiveWindow) = "Explorer" Then
' save selected messages in Explorer window
If CBool(ActiveExplorer.Selection.Count) Then
With ActiveExplorer
For lngC = 1 To .Selection.Count
If .Selection(lngC).Class = olMail Then
MsgSaver3 strPath, .Selection(lngC)
If UserForm1.CheckBox1.Value = True Then
.Selection(lngC).Delete
End If
If UserForm1.CheckBox1.Value = False Then
FiledSubject = "[Filed" & " " & Date & "]" & " " & .Selection(lngC).Subject
.Selection(lngC).Subject = FiledSubject
End If
End If
Next lngC
End With
End If
ElseIf Inspectors.Count Then
' save active open message
If ActiveInspector.CurrentItem.Class = olMail Then
MsgSaver3 strPath, ActiveInspector.CurrentItem
End If
End If
End Sub
Private Sub MsgSaver3(strPath As String, msgItem As Outlook.MailItem)
Dim intC As Integer
Dim intD As Integer
Dim strMsgSubj As String
Dim strMsgFrom As String
strMsgSubj = msgItem.Subject
strMsgFrom = msgItem.SenderName
' Clean out characters from Subject which are not permitted in a file name
For intC = 1 To Len(strMsgSubj)
If InStr(1, ":<>""", Mid(strMsgSubj, intC, 1)) > 0 Then
Mid(strMsgSubj, intC, 1) = "-"
End If
Next intC
For intC = 1 To Len(strMsgSubj)
If InStr(1, "\/|*?", Mid(strMsgSubj, intC, 1)) > 0 Then
Mid(strMsgSubj, intC, 1) = "_"
End If
Next intC
' Clean out characters from Sender Name which are not permitted in a file name
For intD = 1 To Len(strMsgFrom)
If InStr(1, ":<>""", Mid(strMsgFrom, intD, 1)) > 0 Then
Mid(strMsgFrom, intD, 1) = "-"
End If
Next intD
For intD = 1 To Len(strMsgFrom)
If InStr(1, "\/|*?", Mid(strMsgFrom, intD, 1)) > 0 Then
Mid(strMsgFrom, intD, 1) = "_"
End If
Next intD
' add date to file name
strMsgSubj = Format(msgItem.SentOn, "yyyy-mm-dd Hh.Nn.Ss") & " " & "[From " & strMsgFrom & "]" & " " & strMsgSubj & ".msg"
msgItem.SaveAs strPath & strMsgSubj
Set msgItem = Nothing
UserForm1.Hide
End Sub
When you delete the remaining items move up so 2 becomes 1. You never process the original item 2.
Try replacing
For lngC = 1 To .Selection.count
with
For lngC = .Selection.count to 1 step -1
For the same reason a For Each loop does not work when moving or deleting.

VBA To send mail using Filesearch

I have this code to send mail to multiple recipients using Lotus Notes. Right now I need to mention the entire file path for the attachments. My requirement is to use FileSearch method - mention any part of the name of the attachment within * * - so that the files get attached.
Sub Send()
Dim oSess As Object
Dim oDB As Object
Dim oDoc As Object
Dim oItem As Object
Dim direct As Object
Dim Var As Variant
Dim flag As Boolean
Dim cell As Range
Dim r As Excel.Range
Dim Name As String
Dim Annex As String
Dim recp As Variant
Dim cc As Variant
Dim Resp As Long
Resp = MsgBox(prompt:="Do you wish to send to the mail?", Buttons:=vbYesNo + vbInformation + vbDefaultButton2, Title:=AppHeader)
If Resp = vbYes Then
Sheets("Sheet2").Activate
For Each cell In Columns("B").Cells.SpecialCells(xlCellTypeConstants)
If cell.Value Like "?*#?*.?*" And _
LCase(Cells(cell.Row, "E").Value) = "yes" Then
Set oSess = CreateObject("Notes.NotesSession")
Set oDB = oSess.GETDATABASE("", "")
Call oDB.OPENMAIL
flag = True
If Not (oDB.IsOpen) Then flag = oDB.Open("", "")
If Not flag Then
MsgBox "Can't open mail file: " & oDB.SERVER & " " & oDB.FILEPATH
GoTo exit_SendAttachment
End If
On Error GoTo err_handler
'Building Message
recp = Cells(cell.Row, "B").Value
cc = Cells(cell.Row, "C").Value
Set oDoc = oDB.CREATEDOCUMENT
Set oItem = oDoc.CREATERICHTEXTITEM("BODY")
oDoc.Form = "Memo"
oDoc.Subject = "HI" & "-" & Cells(cell.Row, "D").Value
oDoc.sendto = Split(recp, ",")
oDoc.copyto = Split(cc, ",")
oDoc.body = "Dear " & Cells(cell.Row, "A").Value _
& vbNewLine & vbNewLine & _
"Please find attached "
oDoc.postdate = Date
oDoc.SaveMessageOnSend = True
Name = Cells(cell.Row, "F").Value
Annex = Cells(cell.Row, "G").Value
Call oItem.EmbedObject(1454, "", Name)
Call oItem.EmbedObject(1454, "", Annex)
oDoc.Send False
End If
Next cell
MsgBox prompt:="Mail Sent", Buttons:=vbOKOnly + vbInformation, Title:=AppHeader
Exit Sub
'Attaching DATABASE
For Each r In Range("Fpath") '// Change to suit
If r.Value <> vbNullString Then
Call Send
End If
Next
oDoc.visable = True
'Sending Message
exit_SendAttachment:
On Error Resume Next
Set oSess = Nothing
Set oDB = Nothing
Set oDoc = Nothing
Set oItem = Nothing
'Done
err_handler:
If Err.Number = 7225 Then
MsgBox "File doesn't exist"
Else
MsgBox Err.Number & " " & Err.Description
End If
On Error GoTo exit_SendAttachment
Else
Sheets("Sheet1").Activate
End If
End Sub
Any thoughts will be highly appreciated.
It's been years since I have worked with Lotus notes. The last question that I answered on Lotus notes was way back in July 26, 2011 So be gentle on me if I miss any syntax. :p
Application.FileSearch method is no longer supported from XL2007+
Reference: Error message when you run a macro to search for a file in an Office 2007 program: "Run-time error 5111"
In case the above link dies, here is the screenshot.
As mentioned in that link You can use the FileSystemObject object to recursively search directories and to find specific files. Here is how we do that
In case the above link dies, here is the code from that link.
'~~> COURTESY: http://support.microsoft.com/kb/185601
Option Explicit
Dim fso As New FileSystemObject
Dim fld As Folder
Private Sub Command1_Click()
Dim nDirs As Long, nFiles As Long, lSize As Currency
Dim sDir As String, sSrchString As String
sDir = InputBox("Type the directory that you want to search for", _
"FileSystemObjects example", "C:\")
sSrchString = InputBox("Type the file name that you want to search for", _
"FileSystemObjects example", "vb.ini")
MousePointer = vbHourglass
Label1.Caption = "Searching " & vbCrLf & UCase(sDir) & "..."
lSize = FindFile(sDir, sSrchString, nDirs, nFiles)
MousePointer = vbDefault
MsgBox Str(nFiles) & " files found in" & Str(nDirs) & _
" directories", vbInformation
MsgBox "Total Size = " & lSize & " bytes"
End Sub
Private Function FindFile(ByVal sFol As String, sFile As String, _
nDirs As Long, nFiles As Long) As Currency
Dim tFld As Folder, tFil As File, FileName As String
On Error GoTo Catch
Set fld = fso.GetFolder(sFol)
FileName = Dir(fso.BuildPath(fld.Path, sFile), vbNormal Or _
vbHidden Or vbSystem Or vbReadOnly)
While Len(FileName) <> 0
FindFile = FindFile + FileLen(fso.BuildPath(fld.Path, _
FileName))
nFiles = nFiles + 1
List1.AddItem fso.BuildPath(fld.Path, FileName) ' Load ListBox
FileName = Dir() ' Get next file
DoEvents
Wend
Label1 = "Searching " & vbCrLf & fld.Path & "..."
nDirs = nDirs + 1
If fld.SubFolders.Count > 0 Then
For Each tFld In fld.SubFolders
DoEvents
FindFile = FindFile + FindFile(tFld.Path, sFile, nDirs, nFiles)
Next
End If
Exit Function
Catch: FileName = ""
Resume Next
End Function
Once you are able to select the files you can use the below code in a loop to add the attachments
stAttachment = "Blah Blah.Txt"
Set obAttachment = oDoc.CreateRichTextItem("stAttachment")
Set EmbedObject = obAttachment.EmbedObject(EMBED_ATTACHMENT, "", stAttachment)