简体   繁体   中英

Find & replace variable length text in MS Word tables using VBA

I have a long MS Word document with lots of tables and many of tables have hidden text in each cell that contains a text string like “Cell_ID[x,y]” . The string is fixed except that the values of X & Y can be integer values that range from 1-1000.

I want to be able to have a VBA macro that can programmatically remove all occurrences of this text string in each table. If it were a fixed string, then I could simply do a find and replace, but since the values of X & Y can be different lengths, the overall length of the string can vary. The cells that contain this string also have other, non-hidden text that needs to be left alone.

I have code that can loop through all the tables in a document, but I'm not sure how to do the find/replace as described above.

You can use a simple wildcard search and replace. The search pattern would look as follows:

Cell_ID\[[0-9]{1;4},[0-9]{1;4}\]

or

Cell_ID\[[0-9]{1,4},[0-9]{1,4}\]

depending on what is set a your list separator (cf. regional settings). Or you could use an even simpler pattern that would not check whether x and y are digits only:

Cell_ID\[*,*\]

Here is a full VBA sample:

Selection.Find.ClearFormatting

' find hidden text only
Selection.Find.Font.Hidden = True
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .Text = "Cell_ID\[[0-9]{1;4},[0-9]{1;4}\]"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindAsk
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchByte = False
    .MatchAllWordForms = False
    .MatchSoundsLike = False
    .MatchFuzzy = False
    .MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceAll

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM