返回列表 上一主題 發帖

[發問] VBA PostCode format Validation problem!!

[發問] VBA PostCode format Validation problem!!

請問有什麼方法用Excel VBA  驗證英國郵政編碼,
字母+數字的長度是 5 -7 digit
郵政編碼是應該採用以下格式:
LN space  NLL
LNN space  NLL
LLN space  NLL
LNL  space  NLL
LLNL space  NLL
LLNN space  NLL
L是英文字母,N是英文。如果條件不正確,會顯示Msgbox "這是不正確的郵編"
我不知道怎樣用 VBA  驗證以上的格式,因為格式太多
希望有高手可以幫助我,給我一個解決方案. 謝謝!

  1. Sub Validation()
  2.   If IsUKPostcode(Range("H19").Text) Then
  3.     MsgBox "valid post code"
  4.   Else
  5.     MsgBox " invalid post code"
  6.   End If
  7. End Sub
複製代碼
回復 5# hildaliu
表達不清、題意不明確、沒附檔案格式、沒有討論問題的態度~~~~~~以上愛莫能助。

TOP

回復  stillfish00


如果我是想驗証我的excel order form sheet 裡的range (h19)customer post code ...
hildaliu 發表於 2014-11-18 21:49


i just tried this code , is this correct or not?
  1. Sub UK_Postcodes()
  2. Dim RegExp As Object, Collection As Object, RegMatch As Object
  3. Dim Myrange As Range, C As Range, Outstring As String
  4. Set RegExp = CreateObject("vbscript.RegExp")
  5. With RegExp
  6. .Global = False
  7. .Pattern = "^([A-Z]{1,2}\d(\d|[A-Z])?|GIR) \d[A-Z]{2}$"
  8. End With
  9. Set Myrange = Range("h19")
  10. Outstring = ""
  11. Set Collection = RegExp.Execute(ActiveCell.Value)
  12. For Each RegMatch In Collection
  13. Outstring = Outstring & RegMatch
  14. Next

  15. If Range("h19").Value <> "" And Range("h19").Value = Outstring Then
  16. MsgBox "Valid UK Postcode"
  17. Else
  18. MsgBox "Invalid UK Postcode"
  19. End If
  20. Set Collection = Nothing
  21. Set RegExp = Nothing
  22. Set Myrange = Nothing
  23. End Sub
複製代碼

TOP

回復 2# stillfish00


如果我是想驗証我的excel order form sheet 裡的range (h19)customer post code
那vba 要怎樣寫?
我是想按button來驗證post code

Sub validation

If range(h19)= IsUkpostcode then
Msgbox "valid post code"
Else
Msgbox" invalid post code"

End sub

我上面的code是不對的,我不知道怎樣修改
我是新手,在學vba
麻煩到你,不好意思

TOP

回復 2# stillfish00

感謝您的幫助!
你可以為我解釋這代碼是如何操作?
我不是十分明白
非常感謝!

TOP

回復 2# stillfish00
不好意思,2# pattern 稍微改一下,以匹配整個字串而不是字串包含郵遞區號,這樣比較合理。
.Pattern = "^([A-Z]{1,2}\d(\d|[A-Z])?|GIR) \d[A-Z]{2}$"
表達不清、題意不明確、沒附檔案格式、沒有討論問題的態度~~~~~~以上愛莫能助。

TOP

本帖最後由 stillfish00 於 2014-11-18 10:13 編輯

回復 1# hildaliu
寫了一個Function判斷,另外根據wiki多加了判斷條件GIR NLL
  1. Function IsUKPostcode(sText As String) As Boolean
  2.   Dim oRegexp As Object
  3.   
  4.   Set oRegexp = CreateObject("vbscript.regexp")
  5.   With oRegexp
  6.     .ignoreCase = False
  7.     .Pattern = "([A-Z]{1,2}\d(\d|[A-Z])?|GIR) \d[A-Z]{2}"
  8.   End With
  9.   
  10.   IsUKPostcode = oRegexp.Test(sText)
  11. End Function
複製代碼
test
  1. Sub Test()
  2.   Dim ar, x
  3.   ar = Array("F22 5BQ", "FJ29 1GH", "FJ00", "E0 3KK")
  4.   
  5.   For Each x In ar
  6.     If Not IsUKPostcode(CStr(x)) Then MsgBox "這是不正確的郵編:" & x
  7.   Next
  8. End Sub
複製代碼
表達不清、題意不明確、沒附檔案格式、沒有討論問題的態度~~~~~~以上愛莫能助。

TOP

        靜思自在 : 一句溫暖的話,就像往別人身上灑香水,自己會沾到兩三滴。
返回列表 上一主題