替换中使用通配符 - 特定字符数

Wildcard use within Replace - Specific number of characters

我有以下问题:

我想将 link 替换为另一个 sheet。此 link 在宏期间从 "MeasData!E10" 更改为 "MeasData_XXX!E10"(XXX 任何数字)并且可以是宏期间的任何这些。现在我想用当前 sheet.

的 Cell 替换其中一个

问题是,我的单元格包含多个上述字符串,例如:

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

当使用 Cells.Replace 方法时,这将正确地用设置的字符串替换 MeasData_110!E10。但是,如果我要找的 link 不在第一个位置,例如:

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

它将被替换为:

=STRING*MeasData_110!E15

因为我只是使用通配符:

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

我还没有发现是否有通配符 a) 具体字母 和 b) specific/variable 字母数 (0-4)

有人找到解决方案了吗?

如果您知道手机号码,您可以使用下面的

动态传递变量 Cells1、cells2 和 cells3 的值

cells1 = "110!E10"

cells2 = "110!E15"

Cells3 = "110!E20"

str1 = "=MeasData_" & cells1 & "*Measdata_" & cells2 & "*MeasData_" & Cells3

'Debug.Print str1 '打印验证是否需要

你试过正则表达式吗?您需要为此添加对 Microsoft VBScript 正则表达式 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

我认为最快的方法是在循环中使用 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