简体   繁体   English

使用 VBA 在 MS Word 表格中查找和替换可变长度文本

[英]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]” .我有一个很长的 MS Word 文档,里面有很多表格,许多表格在每个单元格中都有隐藏的文本,其中包含一个文本字符串,如“Cell_ID[x,y]”。 The string is fixed except that the values of X & Y can be integer values that range from 1-1000.该字符串是固定的,除了 X 和 Y 的值可以是 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.我希望能够有一个 VBA 宏,它可以以编程方式删除每个表中所有出现的此文本字符串。 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.如果它是一个固定字符串,那么我可以简单地进行查找和替换,但是由于 X 和 Y 的值可以是不同的长度,因此字符串的总长度可能会有所不同。 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:或者您可以使用更简单的模式,该模式不会检查 x 和 y 是否仅为数字:

Cell_ID\[*,*\]

Here is a full VBA sample:这是一个完整的 VBA 示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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