使用Excel公式用有序索引替换花括号内的子字符串

时间:2016-11-22 02:18:06

标签: excel excel-formula

以下是我的Excel数据的示例:



+-----------------------------------------------------------+-----------------------------------------+
| A                                                         | B                                       |
+-----------------------------------------------------------+-----------------------------------------+
| Copyright {year} Company. All rights,reserved.            | Copyright {0} ABB. All rights,reserved. |
+-----------------------------------------------------------+-----------------------------------------+
| The {startDate} and {endDate} must be within {objectType} | The {0} and {1} must be within {2}      |
+-----------------------------------------------------------+-----------------------------------------+
| Unit of measure conversion                                | Unit of measure conversion              |
+-----------------------------------------------------------+-----------------------------------------+




是否有任何Excel公式解决方案将A列花括号内的任何子字符串替换为B列花括号内的有序索引?

我正在考虑使用SUBSTITUTE。但是,我不知道如何在花括号中获取子串并用有序索引替换它。任何想法将不胜感激。谢谢。 :)

1 个答案:

答案 0 :(得分:0)

喜欢这个?

编辑:如果你不知道。
下面的代码是UDF,需要插入VBA编辑器ALT + F11 点击插入 - >模块和复制粘贴代码。 关闭VBA编辑器。 保存时,请记住将文件另存为宏激活文件(xlsm)。

operator bool()

用法:Function Regex(Cell1, Cell2) Dim RE As Object Dim RE2 As Object Set RE = CreateObject("vbscript.regexp") Set RE2 = CreateObject("vbscript.regexp") RE.Pattern = "(\{.*?\})" RE.Global = True RE.IgnoreCase = True RE2.Pattern = "\{(.*?)\}" RE2.Global = True RE2.IgnoreCase = True A = Cell1.Address B = Cell2.Address Set Matches = RE.Execute(Range(A).Value) Set Matches2 = RE2.Execute(Range(B).Value) If Matches.Count <> 0 And Matches2.Count <> 0 And Matches.Count = Matches2.Count Then For myMatchCt = 0 To Matches.Count - 1 For subMtCt = 0 To Matches.Item(subMtCt).SubMatches.Count - 1 If Regex = "" Then Regex = Replace(Range(A).Value, Matches.Item(myMatchCt).SubMatches.Item(subMtCt), Matches2.Item(myMatchCt).SubMatches.Item(subMtCt)) Else Regex = Replace(Regex, Matches.Item(myMatchCt).SubMatches.Item(subMtCt), Matches2.Item(myMatchCt).SubMatches.Item(subMtCt)) End If Next Next Else Regex = Range(A).Value End If End Function

enter image description here