我有以下问题:
我想替换另一张纸的链接。此链接在宏来自" MeasData!E10"到" MeasData_XXX!E10" (XXX任何数字),并且可以是宏中的任何一个。现在我想用当前工作表的Cell替换其中一个。
问题是,我的单元格包含多个上述字符串,例如:
=MeasData_110!E10*MeasData_110!E15*MeasData_110!E20
使用Cells.Replace方法时,这将正确地用设置的字符串替换MeasData_110!E10。但是,如果我要查找的链接不在第一个位置,例如:
=MeasData_110!E20*MeasData_110!E10*MeasData_110!E15
它将被替换为:
=STRING*MeasData_110!E15
因为我只使用通配符:
Worksheets(1).Cells.Replace _
What:="MeasData*!E10", Replacement:=STRING
我还没有发现是否有通配符 a)特定字母 和 b)特定/可变数量的字母(0-4)
有人得到了解决方案吗?
答案 0 :(得分:0)
如果您知道单元格编号,可以使用下面的
动态传递变量Cells1,cells2和cells3
的值cells1 =" 110!E10"
cells2 =" 110!E15"
Cells3 =" 110!E20"
str1 =" = MeasData _" &安培;细胞1& " * Measdata _" &安培;细胞2& " * MeasData _" &安培; Cells3
' Debug.Print str1'打印并验证是否需要
答案 1 :(得分:0)
你试过正则表达式吗?您需要为此
添加对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
答案 2 :(得分:0)
我认为最快的方法是在循环中使用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