2017-02-27 30 views
0

我有一個在郵件接收時執行的vba腳本有問題。 我想轉發一個模板到第一個地址找到收到的郵件。對於我執行和正則表達式,它發現電子郵件的地址到郵件中,閱讀一個html文件(模板)並將其轉發到第一封電子郵件。Outlook VBA規則,加載內存中的數據(靜態?)

幾分鐘後Outlook關機我不知道爲什麼......我認爲這是一個性能問題。所以我想優化腳本,如果我可以在兩次執行之間,我不想兩次讀取模板。可以將它存儲到全局變量中嗎?

的VBA腳本:

Sub GetEmailAndForward(Item As Outlook.MailItem) 

' RegExp 
Dim mailRegExp As RegExp 

' File 
Dim FileTemplate As Integer 
Dim FileProperties As Integer 

' Properties 
Dim splitProperty() As String 

' Email 
Dim DataLine As String 
Dim emails As MatchCollection 
Dim email As String 
Dim forward As Outlook.MailItem 
Dim body As String 
Dim forwardText As String 

' Path 
Dim fileTemplatePath As String 
Dim dirPath As String 
Dim filePropertyPath As String 

dirPath = "C:\OutlookVBA" 

Set mailRegExp = New RegExp 

With mailRegExp 
    .Pattern = "[\_]*([a-z0-9]+(\.|\_*)?)[email protected]([a-z][a-z0-9\-]+(\.|\-*\.))+[a-z]{2,6}" 
    .Global = False 
    .IgnoreCase = True 
End With 

' Get the template 
fileTemplatePath = dirPath & "\template.html" 

' Get the email body to analyse 
body = Item.body 

' Get the first email found 
If mailRegExp.Test(body) Then 
    Set emails = mailRegExp.Execute(body) 
    If emails.Count > 0 Then 
     email = emails.Item(0) 

     Set forward = Item.forward 

     FileTemplate = FreeFile() 
     Open fileTemplatePath For Input As #FileTemplate 

     While Not EOF(FileTemplate) 
      Line Input #FileTemplate, DataLine 
      forwardText = forwardText & DataLine 
     Wend 

     forward.BodyFormat = olFormatHTML 
     forward.HTMLBody = forwardText & forward.HTMLBody 

     Close #FileTemplate 

     If Not IsEmpty(email) Then 
      forward.Recipients.Add email 
      forward.subject = "RE:" & Item.subject 
      forward.Send 
     End If 
    End If 
End If 
End Sub 
+1

如果您有代碼問題,最好發佈代碼。是的,您可以隨時將HTML存儲在全球範圍內。 –

+0

我已添加它。我如何存儲模板? – Pred05

回答

1

您可以使用這樣的事情 - 該功能將只從第一次調用的文件中讀取,之後將使用存儲在靜態變量的文本:

Function GetForWardText(f As String) As String 

    Static rv As String '<< valuje is maintained between calls 

    If Len(rv) = 0 Then 
     rv = CreateObject("scripting.filesystemobject"). _ 
        opentextfile(f, 1).readall() 
    End If 

    ForWardText = rv 

End Function 

在你的代碼,刪除此:

FileTemplate = FreeFile() 
    Open fileTemplatePath For Input As #FileTemplate 

    While Not EOF(FileTemplate) 
     Line Input #FileTemplate, DataLine 
     forwardText = forwardText & DataLine 
    Wend 

,並替換爲:

forwardText = GetForWardText(fileTemplatePath) 
+0

我會盡力謝謝你,你看到腳本中有什麼問題可以解釋Outlook的問題嗎? – Pred05

+0

我沒有看到任何可能導致問題的顯而易見的東西。即使重複閱讀模板文件也不應導致任何問題。 –