Excel VBA - Replace a text inside cell's formula

前端 未结 2 921
生来不讨喜
生来不讨喜 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
    
    0 讨论(0)
  • 2021-01-13 20:54

    Thank you Vityata for your nice explanations, which led me to the answer!

    The problem is, the macro was "First" replacing the name in formulas (i.e to test) and THEN creating the new tab "test".

    For example, if you set this formula in sheet1, cell A1:

    =test2!A1
    

    (Note that you have not created the test2 sheet, yet)

    So you obviously get #REF! error.

    However, if you THEN create test2 tab (by macro or hand), and come back and check cell A1 formula in sheet1, (also refresh by saving the file), it STILL shows #REF! error, even now test2 tab is really there! (You need to Double click on the cell, and press enter, for that to UPDATE)

    As a result, I changed my macro so that it FIRST creates the test tab, and THEN manipulate those formulas.

    0 讨论(0)
提交回复
热议问题