regex - VBA macro in Excel 2007. I want to use Regular Expressions in Excel VBA to replace "He" with "She", "he" with "she", "Him" with "her" -
sub test() dim strtest string dim strtemp string strtest = sheet1.cells(1, 1).value msgbox re6(strtest) sheet1.cells(2, 1).value = re6(strtest) end sub function re6(strdata string) dim re object 'rematches object dim p string, string dim q string, b string dim r string, c string dim s string, d string dim t string, e string dim u string, f string dim v string, g string dim w string, h string dim n integer set re = createobject("vbscript.regexp") p = "(?:^|\b)he" = "she" q = "(?:^|\b)he" b = "she" r = "(?:^|\b)him" c = "her" s = "(?:^|\b)him" d = "her" t = "(?:^|\b)himself" e = "herself" u = "(?:^|\b)himself" f = "herself" v = "(?:^|\b)his" g = "her" w = "(?:^|\b)his" h = "her" 'this section replaces "he" with"she" re .multiline = true .global = true .ignorecase = false .pattern = p end re6 = re.replace(strdata, a) 'this section replaces "he" "she" re .multiline = true .global = true .ignorecase = false .pattern = q end re6 = re.replace(strdata, b) ' 'this section replaces "him" "her" re .multiline = true .global = true .ignorecase = false .pattern = r end re6 = re.replace(strdata, c) 'this section replaces "him" "her" re .multiline = true .global = true .ignorecase = false .pattern = s end re6 = re.replace(strdata, d) 'this section replaces "himself" "herself" re .multiline = true .global = true .ignorecase = false .pattern = t end re6 = re.replace(strdata, e) 'this section replaces "himself" "herself" re .multiline = true .global = true .ignorecase = false .pattern = u end re6 = re.replace(strdata, f) 'this section replaces "his" "her" re .multiline = true .global = true .ignorecase = false .pattern = v end re6 = re.replace(strdata, g) 'this section replaces "his" "her" re .multiline = true .global = true .ignorecase = false .pattern = w ' re6 = re.replace(strdata, h) end end function
when run code on piece of text:
james has settled effortlessly in new class. has shown seriousness , demonstrated traits of serious student in first half of term. optimistic positive attitude towards work, if not relent, yield positive dividends. however, james needs respond positively prompts on getting himself better organised in school. wish him, him best in second half of term.
i "his" replaced "her". if comment out last bit "him" replaced "her". welcome.
the issue repeatedly replacement on strdata
, opposed result of each replacement; is, take original string, replace "he" "she", , store in re6. take original string again, replace "he" "she", , store in re6, overwriting first replacement, , on , on.. why see results of last replacement.
to fix it, leave first replacement
re6 = re.replace(strdata, a)
but change of other replacements
re6 = re.replace(re6, b) <-- b-h
this give desired output.
Comments
Post a Comment