验证美国和加拿大邮政编码的正则表达式-Runtime Error 438 Excel

时间:2019-05-23 19:45:52

标签: regex excel vba zipcode

我已编写此代码来帮助验证我们供应商表格中的邮政编码单元格。我希望它在进入下一个单元格时进行验证。我收到运行时438错误:当我尝试移至下一个单元格时,对象不支持此属性或方法。我需要此代码来验证所有美国和加拿大的邮政编码(正在使用英语)。

我尝试通过数据验证来做到这一点,我可以拥有美国或加拿大,但不能同时拥有这两个国家。

Private Sub worksheet_selectionchange(ByVal target As Range)
    If Selection.Count = 1 Then
        'Erm, nothing to do here....
    ElseIf Not Intersect(target, Range("B39,B50")) Is Nothing Then
        Exit Sub
    End If

    Dim searchRange     As Excel.Range
    Dim cell            As Variant
    Dim RegEx           As Object

    Set RegEx = CreateObject("VBScript.RegExp")

    With RegEx
        .Pattern = "^(\d{5}(-\d{4})?|[A-CEGHJ-NPRSTVXY]\d[A-CEGHJ-NPRSTV-Z] ?\d[A-CEGHJ-NPRSTV-Z]\d)$"
        .Global = True
        .MultiLine = True
    End With

    Set searchRange = ActiveSheet.Range("B39,B50")
    For Each cell In searchRange.Cells
       If RegEx.IsMatch(subjectString, "^(\d{5}(-\d{4})?|[A-CEGHJ-NPRSTVXY]\d[A-CEGHJ-NPRSTV-Z] ?\d[A-CEGHJ-NPRSTV-Z]\d)$") Then
            MsgBox ("Valid ZIP code")
        Else
            MsgBox ("Invalid ZIP code")
        End If
    Next cell
    Set searchRange = Nothing
    Set RegEx = Nothing

End Sub

调试行是

  If RegEx.IsMatch(subjectString, "^(\d{5}(-\d{4})?|[A-CEGHJ-NPRSTVXY]\d[A-CEGHJ-NPRSTV-Z] ?\d[A-CEGHJ-NPRSTV-Z]\d)$") Then

我不在乎是否使用数据验证或VBA,我只需要准备一些东西即可对此进行验证。请在您的回复中详细说明。我对VBA和Regex仍然相当“绿色”。

1 个答案:

答案 0 :(得分:0)

应该工作(假设模式正确):

Private Sub worksheet_selectionchange(ByVal target As Range)

    Static RegEx As Object '<<
    Dim searchRange As Range

    Set searchRange = Application.Intersect(Target, Me.Range("B39, B50"))
    If searchRange Is Nothing then Exit Sub

    'see if we need to set up the regexp object
    If RegEx Is Nothing Then
        Set RegEx = CreateObject("VBScript.RegExp")
        With RegEx
            .Pattern = "^(\d{5}(-\d{4})?|[A-CEGHJ-NPRSTVXY]\d" & _
                       "[A-CEGHJ-NPRSTV-Z] ?\d[A-CEGHJ-NPRSTV-Z]\d)$"
            .Global = True
            .MultiLine = True
        End With
    End If

    For Each cell In searchRange.Cells
        MsgBox IIf(RegEx.Test(cell.Value), "Valid", "Invalid") & " ZIP code"
    Next cell

End Sub

编辑:如果您要在Worksheet_Change中做两件事,则可以将所有代码合并到一个事件处理程序中,或者执行以下操作:

Private Sub worksheet_change(ByVal target As Range)
    HandleFirstThing Target
    DoSomethingElse Target
End Sub

Sub HandleFirstThing(Target As Range)
   'first thing to handle
End Sub

Sub DoSomethingElse(Target As Range)
   'next thing to handle
End Sub