如何将城市、州和邮政编码分析为单独的值

原始产品版本: Microsoft Office Access 2003、Microsoft Office Access 2007、Access 2010
原始 KB 编号: 168798

摘要

本文提供了一个过程,用于将包含美国城市、州和邮政编码信息的单个变量分析为三个单独的变量。 例程支持:

  • 5 位或 9 位邮政编码。
  • 如果前面有逗号) ,则多字状态名称 (。
  • 任意数量的中间空格。

支持的输入示例:

纽约,纽约,99999
纽约,纽约,99999-9999
纽约,纽约州 99999-9999
纽约 NY 99999

更多信息

警告:你对本文中提供的代码/宏的任何使用都由你自行承担风险。 Microsoft 按“原样”提供此代码/宏,不提供任何形式的明示或暗示担保,包括但不限于适销性和/或特定用途适用性的默示保证。

注意:在以下示例代码中,行尾的下划线 (_) 用作行延续字符。 对于不支持行延续字符的 BASIC 版本,请在重新创建此代码时删除行尾的下划线,并合并以下行。

如果在地址中找不到逗号,则按以下顺序分析字段:邮政编码、州、城市 如果至少有一个逗号存在,则假定字段在 City 和 State 之间,并且按其他顺序分析字段:City、State、Zip Code

分步示例

  1. 输入以下代码:

    VB
    Function CutLastWord (ByVal S As String, Remainder As String) _
             As String
        ' CutLastWord: returns the last word in S.
        ' Remainder: returns the rest.
        '
        ' Words are separated by spaces
        '
        Dim I           As Integer, P As Integer
        S = Trim$(S)
        P = 1
        For I = Len(S) To 1 Step -1
            If Mid$(S, I, 1) = " " Then
                P = I + 1
                Exit For
            End If
        Next I
        If P = 1 Then
            CutLastWord = S
            Remainder = ""
        Else
            CutLastWord = Mid$(S, P)
            Remainder = Trim$(Left$(S, P - 1))
        End If
    End Function
    
    Sub ParseCSZ (ByVal S As String, City As String, State As String, _
        Zip             As String)
        Dim P           As Integer
        '
        ' Check for comma after city name
        '
        P = InStr(S, ",")
        If P > 0 Then
            City = Trim$(Left$(S, P - 1))
            S = Trim$(Mid$(S, P +        '
            ' Check for comma after state
            '
            P = InStr(S, ",")
            If P > 0 Then
                State = Trim$(Left$(S, P - 1))
                Zip = Trim$(Mid$(S, P + 1))
            Else        ' No comma between state and zip
                Zip = CutLastWord(S, S)
                State = S
            End If
        Else        ' No commas between city, state, or zip
            Zip = CutLastWord(S, S)
            State = CutLastWord(S, S)
            City = S
        End If
        '
        ' Clean up any dangling commas
        '
        If Right$(State, 1) = "," Then
            State = RTrim$(Left$(State, Len(State) - 1))
        End If
        If Right$(City, 1) = "," Then
            City = RTrim$(Left$(City, Len(City) - 1))
        End If
    End Sub
    
  2. 若要进行测试,请创建包含四个文本框的窗体, (txtAddress、txtCity、txtState、txtZip) 和命令按钮。 添加以下代码:

    VB
    Sub Command1_Click()
        Dim City        As String, State As String, Zip As String
        ParseCSZ txtAddress, City, State, Zip
        txtCity = City
        txtState = State
        txtZip = Zip
    End Sub
    
  3. 显示窗体,在 txtAddress 中键入地址,然后单击命令按钮。 其他三个字段应包含已分析的值。