代码之家  ›  专栏  ›  技术社区  ›  Gary.Ray

vba-解析电子邮件文本以访问2000类实例

  •  1
  • Gary.Ray  · 技术社区  · 15 年前

    我现在为客户机维护一个旧的vba/access 2000应用程序。他们有一个客户用类似这样的文本通过电子邮件发送订单

    Contact: Peggy Hill
    Company: Arlen Residential Mortgage Finance Co
    Address: 43456 South 18939 West, Suite 47995
    City: Arlen City
    ContactState: TX
    ContactZip: 88888
    Phone: 8019990000
    Email: peggy.hill@arlenmortgage.com
    
    DateOrdered: 4/6/09
    DateDue: 4/15/09
    

    等。。。

    应用程序有一个具有所有属性的VBA类,但无法将数据解析为适当的字段。我的客户想要一个表单,他们可以在其中粘贴电子邮件中的文本,将其解析为字段进行验证,然后写入数据库。

    问题/事实:

    1. 每个值都用'valuename:“token”进行设置。
    2. 根据电子邮件客户端如何管理字符串,每行末尾可能有或没有CRLF。
    3. 缺少的值将仅具有标记、无“”或空空间。

    我想创建一个 CreateOrder(OrderText As String) 函数可以从窗体中读取文本,但我不知道如何处理VBA中的解析。
    我开始创建一个带有预先输入的令牌的二维数组,但这看起来有些笨拙,因为我必须读取数组中的下一项,以确定何时停止接受上一个令牌的数据。

    建议?

    1 回复  |  直到 9 年前
        1
  •  3
  •   Mitch Wheat    15 年前

    这相当简单;请添加您自己的错误检查。需要添加对“Microsoft脚本运行时”的引用

    Public Function Parse(msg As String) As Dictionary
       Dim i As Integer, pos As Integer
       Dim line As Variant
       Dim lines() As String
       Dim dict As New Dictionary
    
       lines = Split(msg, vbCrLf)
       For Each line In lines()
          pos = InStr(1, line, ":", vbTextCompare)
          If pos <> -1 Then
            dict.Add Trim$(Left$(line, pos - 1)), Trim$(Right$(line, Len(line) - pos))
          End If
       Next
    
       Rem: Access values like this (with null checks):
       Rem:    dict("Contact"), dict("Address")
    
       Set Parse = dict
    
    End Function
    

    我使用它创建了一个带有文本框和按钮的简单表单,并将其添加到按钮单击事件:

    Private Sub Command2_Click()
        Dim dict As Dictionary
    
        Text0.SetFocus
        Set dict = Parse(Text0.text)
    
        Debug.Print dict("Contact"), dict("Address")
    
        Rem clear up when done
        Set dict = Nothing
    
    End Sub