使用VBA脚本将每个文本文件的第三行替换为字符串

时间:2014-07-24 13:38:55

标签: vba outlook outlook-vba

我使用下面的代码将电子邮件作为单独的文本文件导出到系统文件夹。我需要在循环中将文本文件中的第三行替换为所有文本文件的字符串。任何人都可以建议溶液

' General Declarations
Option Explicit

' Public declarations
Public Enum olSaveAsTypeEnum
  olSaveAsTxt = 0
  olSaveAsRTF = 1
  olSaveAsMsg = 3
End Enum

Sub COBExport_MailasMSG()
' Routine will take all selected mails and export them as .MSG files to the
' directory defined by
' Error Handling
On Error Resume Next

' Varaiable Declarations
Dim objItem As Outlook.MailItem
Dim strExportFolder As String: strExportFolder = "I:\Documents\"
Dim strExportFileName As String
Dim strExportPath As String
Dim objRegex As Object
Dim OldName As String, NewName As String

' Initiate regex search
Set objRegex = CreateObject("VBScript.RegExp")
With objRegex
.Pattern = "(\s|\\|/|<|>|\|\|\?|:)"
.Global = True
.IgnoreCase = True
End With

' Check if any objects are selected.
If Application.ActiveExplorer.Selection.Count = 0 Then
   MsgBox ("No item has been selected.")
Else
    ' Cycle all selected objects.
    For Each objItem In Application.ActiveExplorer.Selection
        ' If the currently selected item is a mail item we can proceed
        If TypeOf objItem Is Outlook.MailItem Then
            ' Export to the predefined folder.
            strExportFileName = objRegex.Replace(objItem.Subject, "_")
            strExportPath = strExportFolder & strExportFileName & ".txt"


            objItem.SaveAs strExportPath, olSaveAsTxt
            'MsgBox ("Email saved to: " & strExportPath)
            OldName = Dir(strExportPath)
    NewName = Left(strExportPath, Len(strExportPath) - Len(OldName)) & _
              Left(OldName, Len(OldName) - 4) & "Dir" & _
              CStr(Format(FileDateTime(strExportPath), "ddmmyyhhmmss")) & ".txt"
     Name strExportPath As NewName


        Else
            ' This is not an email item.
        End If
    Next 'objItem
End If



' Clear routine memory
Set objItem = Nothing
Set objRegex = Nothing

End Sub

1 个答案:

答案 0 :(得分:0)

这个解决方案可能会削减你想要做的事情的中间人。它不是在导出文件后更新文件,而是为了我们之前只编辑电子邮件的正文!

警告这会暂时改变您的电子邮件正文。如果进程失败或代码未正确使用,您可能会永久损坏电子邮件。你应该在你不关心的邮件上测试这个。

我确实尝试复制邮件,以便我们可以编辑副本,但最后是另一份邮件副本,在Outlook中,我无法以编程方式删除。因此,这个解决方案似乎更清晰。

' declaration to go with the others
Dim strEmailBodybackup As String

' this will go in your for loop
' Save the body so that we can restore it after.
strEmailBodybackup = objItem.Body

' Edit the body of the mail to suit needs.
objItem.Body = Replace(objItem.Body, "scantext", "Tscanfile", , 1, vbTextCompare)

' Process the export like in your question

' Restore the body of the original mail 
objItem.Body = strEmailBodybackup

您可以查找替换命令here