Free Support Forum -

Range.Replace with Regex(".*") throws exception

The following code fragment, used to clear the contents of a table cell, throws a null reference exception:

Dim rgxAll as New Regex(".*")

myCell.Range.Replace(rgxAll, "")

I get the same result if the Regex is ".*." and I avoid replacing the -1 at the end of cell.range.text

This is no longer a problem for me since I should have been using Range.Delete() in the first place, but you may want to look into it.



Thank you for the report. We'll fix it so it deletes text instead of throwing.

I fixed the null reference exception, but you are right, to clear a range it is better to use Range.Delete.

Even I though I fixed the null reference exception, Range.Replace is not so useful for deleting lots of text because it cannot replace text that contains paragraph, cell or section breaks. In you pattern ".*" the end of cell character will be captured and Range.Replace with throw explaining that it cannot replace a break.

Just to illisutrate here is a piece of code that works for deleting content of a cell in case the cell does not contain any other paragraph break characters:

cell.Range.Replace(new Regex(".*[^\x07]"), "");

As you can see it is somewhat ugly and limited in functionality, just use Range.Delete.