Word VBA: iterating through characters incredibly slow -
i have macro changes single quotes in front of number apostrophe (or close single curly quote). typically when type "the '80s" in word, apostrophe in front of "8" faces wrong way. macro below works, incredibly slow (like 10 seconds per page). in regular language (even interpreted one), fast procedure. insights why takes long in vba on word 2007? or if has find+replace skills can without iterating, please let me know.
sub fixnumericalreversequotes() dim char range debug.print "starting " + cstr(now) selection total = .characters.count ' looking ahead 1 character, need @ least 2 in selection if total < 2 return end if x = 1 total - 1 a_code = asc(.characters(x)) b_code = asc(.characters(x + 1)) ' want convert single quote in front of number apostrophe ' trying use numerical comparisons speed if (a_code = 145 or a_code = 39) , b_code >= 48 , b_code <= 57 .characters(x) = chr(146) end if next x end debug.print "ending " + cstr(now) end sub
beside 2 specified (why...? , how without...?) there implied question – how proper iteration through word object collection. answer – use obj.next property rather access index. is, instead of:
for = 1 activedocument.characters.count 'do activedocument.characters(i), e.g.: debug.pring activedocument.characters(i).text next
one should use:
dim ch range: set ch = activedocument.characters(1) 'do ch, e.g.: debug.print ch.text set ch = ch.next 'note iterating loop until ch nothing
timing: 00:03:30 vs. 00:00:06, more 3 minutes vs. 6 seconds.
found on google, link lost, sorry. confirmed personal exploration.