保存附件时替换文件名中的特殊字符

时间:2018-12-03 09:38:40

标签: vba outlook

我制作了一个脚本来自动保存附件并打印。

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

包含特殊字符(例如#&)的附件会使脚本崩溃。

我想要一种用其他方式替换特殊字符的方法。

2 个答案:

答案 0 :(得分:1)

我最近构造了一个函数,可以从字符串中删除所有元音。也许这适合您

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

然后您可以尝试在Sub中设置文件名

FileNameNoSpecChars = REMOVEVOWELS(objAttach.FileName)

下一步,使用新变量保存文件

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

希望这会有所帮助。

答案 1 :(得分:1)

我能够使用以下代码解决问题:

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