I am trying to write a VBA function in Access that replaces the words in the address field with the standard US Postal Abbreviations . I understand that this will never be perfect, but I want to at least make simple reductions (without having to purchase address formatting software), for example
input output ------- ------------- North -> N Street -> ST Drive -> DR Lane -> LN
I thought about using a simple table to store a row and a replacement row, and then scroll through that table / recordset to do a simple search and replace using the Replace()
function, for example. using immediate window
:
?Replace("123 North 3rd St", "North", "N", compare:=vbTextCompare) 123 N 3rd St
However, this method can potentially cause errors, for example.
?Replace("123 Northampton St", "North", "N", compare:=vbTextCompare) 123 Nampton St
My initial strategy was to create a replacement table with regex patterns and replacement strings, and then scroll through this table for a more precise search and replacement.
pattern abbrev ------------------- ------------ {pattern for North} N {pattern for Street} ST
I realized that RegEx could be crowded here, especially since I am going to cycle through address fields many times in the database, but could not think of an easier way to use the Replace()
function ( Update : see the Answers from @ mwolfe02 and @ Cylian and hybrid solution).
In the above example, I want to search for the words "North" and "Street" if they either exist as a word in a line (thus separated by two spaces), or at the end of a line or the beginning of a line. This covers most situations that need to be shortened. eg
address formatted ---------------------- -------------------------- 123 North 3rd St -> 123 N 3RD ST 123 ABC Street North -> 123 ABC ST N North 3rd Street -> N 3RD ST 123 North Northampton St -> 123 N NORTHAMPTON ST
As in these examples, I want to replace all instances of the template in a string. I also convert everything to uppercase (I can use UCase()
for the final result without any problems).
Does anyone know of an existing module that does such things? Can someone help with pattern matching like in the examples above? For additional credit, I am also interested in creating a rule in the table for formatting mailboxes, for example.
address formatted ---------------------- -------------------------- PO Box 345 -> PO BOX 345 PO Box 345 -> PO BOX 345 Post Office Box 345 -> PO BOX 345 PO. Box 345 -> PO BOX 345 PO Box 345 -> PO BOX 345
This post provides the following pattern for recognizing some PO boxes "^ \ s * P.?\s? O.?\sB [Oo] [Xx]". (though not the third example above). Again, I am not so comfortable with matching and replacement sets to figure out how to write this more accurate replacement function. Is there a RegEx / Access specialist that can help?