replace中使用通配符 – 特定数量的字符

我有以下问题:

我想要replace另一个工作表的链接。 macros从“MeasData!E10”到“MeasData_XXX!E10”(XXX任意数字)时,该链接将变化,在macros期间可以是任何这些链接。 现在我想用当前工作表的单元格replace其中的一个。

问题是,我的单元格包含不止一个像上面的string,例如:

=MeasData_110!E10*MeasData_110!E15*MeasData_110!E20 

当使用Cells.Replace方法时,这将正确地将MeasData_110!E10replace为设定的string。 但是,如果我所寻找的链接不在第一位,例如:

 =MeasData_110!E20*MeasData_110!E10*MeasData_110!E15 

它将被replace为:

 =STRING*MeasData_110!E15 

因为我只是使用通配符:

 Worksheets(1).Cells.Replace _ What:="MeasData*!E10", Replacement:=STRING 

我还没有发现是否有a)特定字母的通配符和b)特定/可变数量的字母(0-4)

有人得到了解决scheme?

我认为最快的方法是在循环中使用Replace()

 Sub MM() Dim foundCell As Excel.Range Dim foundAddress As String Dim findString As String Dim replaceString As String findString = "MeasData!E10" replaceString = Range("AD48").Value Set foundCell = Sheets(1).Cells.Find(What:=findString, LookIn:=xlFormulas, LookAt:=xlPart) If Not foundCell Is Nothing Then foundAddress = foundCell.Address Do With foundCell .Formula = Replace(.Formula, findString, replaceString) End With Set foundCell = Sheets(1).Cells.FindNext(foundCell) Loop While Not foundCell Is Nothing End If End Sub 

要么

你可以,如果你愿意,可以通过后期绑定来使用VBScript.RexExp对象,如下所示:

 Function ReplaceAllWith(old_string As String, pattern As String, new_string As String) As String With CreateObject("VBScript.RegExp") .pattern = pattern .Global = True If .Test(old_string) Then ReplaceAllWith = .Replace(old_string, new_string) Else ReplaceAllWith = old_string End If End With End Function 

把上面的代码插入到你的模块中,然后像这样使用:

 For Each cell In Sheets(1).UsedRange.Cells If cell.HasFormula Then cell.Formula = ReplaceAllWith(cell.Formula, "MeasData(_[\d]{3})?!E10", Range("AD48").Value) End If Next 

如果你知道单元格号码,你可以使用下面的

dynamic传递variablesCells1,Cells2和Cells3的值

cells1 =“110!E10”

cells2 =“110!E15”

Cells3 =“110!E20”

str1 =“= MeasData_”&cells1&“* Measdata_”&cells2&“* MeasData_”&Cells3

'Debug.Print str1'打印并validation您是否需要

你尝试过正则expression式吗? 您需要为此添加对Microsoft VBScript正则expression式5.5的引用

  Sub test() Dim a As String a = "=MeasData_110!E20*Measdata_110!E10*MeasData_110!E15*Measdata_123!E10" a = ReplaceNumbers(a, "MeasData_STRING!E10") MsgBox a End Sub Private Function ReplaceNumbers(inputString As String, replacement As String) As String Pattern = "Meas[dD]ata_([0-9]{1,})\!E10" output = inputString Dim re As New RegExp re.Pattern = Pattern re.Global = True: re.MultiLine = True If re.test(inputString) Then ReplaceNumbers = re.Replace(inputString, replacement) Else ReplaceNumbers = inputString End If End Function