How to replace the function in excel
我有一个包含大量公式的巨大 Excel 文件。在单元格中,有一堆对旧函数 funcA 的引用,它将采用 1 个参数。该参数还可以嵌入其他函数,或其他单元格值,或公式。像这样
1 2 | =C1+C2+funcA(C3)/2 =funcA(C4+AnotherFun(B1)) |
现在我需要将所有 funcA 更改为 funcB。然而, funcB 有两个参数。我需要来自 funcA 的原始参数作为 funcB 的第一个参数,但第二个参数为 0。所以替换后,它看起来像这样
1 2 | =C1+C2+funcB(C3,0)/2 =funcB(C4+AnotherFun(B1),0) |
当我尝试替换 funcA 时 --> funcB excel 被拒绝,因为 funcB 需要两个参数。另外我还需要想办法在函数调用中添加一个',0'。我想到了 RegEx 匹配,但似乎 Excel 不支持这个。
我能做什么?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | Option Explicit Sub ReplaceFunction() Dim ufr As Range, ufrng As Range Dim b As Long, i As Long, x As Long, f As String Dim oldf As String, newf As String, p As String oldf ="funcA(" newf ="funcB(" p =", 0)" On Error Resume Next Set ufrng = Worksheets("sheet3").Cells.SpecialCells(xlCellTypeFormulas) On Error GoTo 0 If Not ufrng Is Nothing Then For Each ufr In ufrng f = ufr.Formula b = 0 x = InStr(1, f, oldf, vbTextCompare) If x > 0 Then For i = x + Len(oldf) To Len(f) 'are there nested functions? If Mid(f, i, 1) =")" Then b = b - 1 ElseIf Mid(f, i, 1) ="(" Then b = b + 1 End If 'ending bracket for funcA If b = -1 Then 'add parameter f = Application.Replace(f, i, 1, p) 'change function f = Replace(expression:=f, Find:=oldf, Replace:=newf, compare:=vbTextCompare) 'no reason to continue Exit For End If Next i 'change formula ufr.Formula = f End If Next ufr End If End Sub Function funcA(i As Integer) funcA = i End Function Function funcB(i As Integer, j As Integer) funcB = i * j End Function Function AnotherFunc(i As Integer) AnotherFunc = i End Function |