使用 Regular Expressions 提取 Excel 儲存格內容為Email的字串(In-Cell Function)

因為電子報有近2千封的退信,在Outlook 2013 一封一封的開啟並複製 email address 是非常耗時的,因此才想到用 VBA 來完成這樣的工作。

這個流程分2部份,第1部份是從 Outlook 2013 匯出 CSV 格式的記錄檔,第2部份是在 Excel 中寫入功能模組。

第1部份:從 Outlook 2013 匯出 CSV 格式的記錄檔

  1. 開啟匯入及匯出精靈並選擇『匯出至檔案』

  2. 選擇『逗點分隔值』

  3. 先將退信集中在一個資料夾,再匯出 CSV 檔

  4. 指定儲存路徑及檔名

  5. 只輸出郵件本文到 CSV檔

第2部份:在Excel中寫入功能模組

  1. 點選 Visual Basic

  2. 新增模組

  3. 增加 RE 引用項目:工具 ➠ 設定引用項目 ➠ Microsoft VBScript Regular Expression 5.5 打勾

  4. 在模組下增加以下的程式碼
  5. Function RegExGet(aString As String) As Variant
     Dim regEx As New RegExp
     Dim newArray() As String
     Dim x As Integer
     Dim y As Integer

     regEx.Pattern = "[a-zA-Z0-9_]+@[a-zA-Z0-9\._]+" // 電子郵件的Regular Expressions
     regEx.IgnoreCase = True
     regEx.Global = True
     Set matches = regEx.Execute(aString)
     x = matches.Count

     ReDim newArray(x - 1) As String
     Count = 0

     For Each Match In matches
        newArray(cnt) = Match.Value
        cnt = cnt + 1
     Next

     RegExGet = newArray()

    End Function
    程式碼出處:UDF8: RegExGet - return matches of regular expressions in excel (excel VBA)

  6. A欄是電子郵件本文,B欄則是我們要的資料,例如在B2欄中輸入=RegExGet(A2),就可以篩選出email address