Why don't you isolate the table writing by itself... in a function of some sort, then when writing out the entire file, you just account for the opening and closing html and body tags in the sub? Shouldn't have to "replace" anything that way...