No 0ne
No 0ne

Reputation: 61

Replace special characters in filename when saving attachment

I made a script to save attachments automatically and print them.

Sub SaveAttachment(Item As MailItem)
    If Item.Class = olMail Then
        If Item.Attachments.Count > 0 Then
            Dim objAtt As Outlook.Attachments
            Set objAtt = Item.Attachments
            For Each objAttach In objAtt
                objAttach.SaveAsFile "C:\PDFInvoices\" & _
                        Item.Subject & "_" & objAttach.FileName '
            Next
            Set objAtt = Nothing
        End If
    End If
End Sub

An attachment containing special characters such as # or & makes the script crash.

I want a way to replace, the special characters by something else.

Upvotes: 0

Views: 1654

Answers (2)

No 0ne
No 0ne

Reputation: 61

I was able to fix the problem using the following code :

Public Sub saveAttachtoDiskRule(itm As Outlook.MailItem)
Dim strSubject As String, strExt As String
Dim objAtt As Outlook.Attachment
Dim saveFolder As String

Dim enviro As String
enviro = CStr(Environ("ngallouj"))
saveFolder = enviro & "C:\PDFInvoices\"

For Each objAtt In itm.Attachments
DateFormat = Format(Date, "yyyy-mm-dd ")

file = saveFolder & DateFormat & objAtt.DisplayName
 objAtt.SaveAsFile file
 Next

 Set objAtt = Nothing
 End Sub

Upvotes: 1

Tim Stack
Tim Stack

Reputation: 3248

I have recently constructed a function which removes all vowels from a string.. Perhaps this suits you

Function REMOVEVOWELS(Txt) As String
'Removes all vowels from the Txt argument
Vowels = Array("A", "E", "I", "O", "U") 'Replace vowels with special chars

For Each a In Vowels
    Txt = Replace(Txt, a, "")
Next a
REMOVEVOWELS = Txt
 End Function

Then you could try setting the file name in your Sub

FileNameNoSpecChars = REMOVEVOWELS(objAttach.FileName)

Next, save the file with the new variable

        For Each objAttach In objAtt
            objAttach.SaveAsFile "C:\PDFInvoices\" & _
                    Item.Subject & "_" & FileNameNoSpecChars  '
        Next

Hope this helps.

Upvotes: 2

Related Questions