Excel VBA - Replace a text inside cell's formula

前端 未结 2 920
生来不讨喜
生来不讨喜 2021-01-13 19:47

I have faced a strange thing in Excel VBA coding.

I have a sheet full of formulas, each refers to the cells in other sheets.

This is a sample formula in cell

2条回答
  •  被撕碎了的回忆
    2021-01-13 20:49

    What you can do is to read the formula to a string, replace in the string and pass the string as a new formula like this:

    Sub TestMe()
    
        Dim oldStr$, newStr$
    
        oldStr = "'General Inputs & Summary'"
        newStr = "'test'"
        newStr = Replace(Range("A1").Formula, oldStr, newStr)
        Range("A1").Formula = newStr
    
    End Sub
    

    To illustrate the ' take a look at this example:

    Sub TestMe()
    
        Dim a As Range
        Dim b As String
        Set a = Range("A1")
    
        b = "'12"
        a = b
    
        Debug.Print a 'prints 12
        Debug.Print b 'prints '12
    
    End Sub
    

    The cell in A1 is formatted as text and contains the ', but the printed value is without it.


    Edit: In general, the ' is needed only when the worksheet name contains spaces, like this one - General Inputs & Summary. Without spaces in the name, like test, it is not quite needed, thus this example works as well:

    Public Sub TestMe()
    
        Dim a As Range: Set a = Range("A1")
        Dim oldStr$, newStr$
    
        a.Formula = "=IF('GI S'!B6="","",'GI S'!B6)"
    
        oldStr = "'GI S'"
        newStr = "'test'"
        Range("A1").Formula = Replace(Range("A1").Formula, oldStr, newStr)
    
    End Sub
    

提交回复
热议问题