如何在excel中替换功能

时间:2019-05-13 22:32:47

标签: excel excel-formula

我有一个包含大量公式的巨大excel文件。对于in单元格,有许多对旧函数funcA的引用,该函数将带有1个参数。该参数也可以嵌入其他函数或其他单元格值或公式。像这样

=C1+C2+funcA(C3)/2 
=funcA(C4+AnotherFun(B1))

现在我需要将所有funcA更改为funcB。但是,funcB有两个参数。我需要funcA的原始参数作为funcB的第一个参数,但第二个参数为0。所以替换后,它看起来像这样

=C1+C2+funcB(C3,0)/2 
=funcB(C4+AnotherFun(B1),0)

当我尝试执行替换funcA时-> funcB excel被拒绝,因为funcB需要两个参数。另外,我仍然需要考虑一种在函数调用中添加“,0”的方法。我认为是RegEx匹配项,但似乎Excel不支持此功能。

我该怎么办?

1 个答案:

答案 0 :(得分:1)

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