Search code examples
excelformulainverse

Formula and its inverse in Excel


I'm trying to implement ad easy function in Excel. I want the user input a value in the cell A1, and in the cell A2 the function should be "The value in A1"+1. This is a super easy task in Excel, but I really need a different behavior: when the user inputs a value in A2, Excel should compute "The value in A2"-1 and put this value in A1 (the inverse formula of the previous one).

Is there an easy way to do this?

Thank you.


Solution

  • Place the following Event macro in the worksheet code area:

    Private Sub Worksheet_Change(ByVal Target As Range)
        Dim A1 As Range, A2 As Range
        Set A1 = Range("A1")
        Set A2 = Range("A2")
    
        If Intersect(Union(A1, A2), Target) Is Nothing Then Exit Sub
    
        Application.EnableEvents = False
            If Not Intersect(A1, Target) Is Nothing Then
                A2.Value = A1.Value + 1
            Else
                A1.Value = A2.Value - 1
            End If
        Application.EnableEvents = True
    End Sub
    

    Because it is worksheet code, it is very easy to install and automatic to use:

    1. right-click the tab name near the bottom of the Excel window
    2. select View Code - this brings up a VBE window
    3. paste the stuff in and close the VBE window

    If you have any concerns, first try it on a trial worksheet.

    If you save the workbook, the macro will be saved with it. If you are using a version of Excel later then 2003, you must save the file as .xlsm rather than .xlsx

    To remove the macro:

    1. bring up the VBE windows as above
    2. clear the code out
    3. close the VBE window

    To learn more about macros in general, see:

    http://www.mvps.org/dmcritchie/excel/getstarted.htm

    and

    http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

    To learn more about Event Macros (worksheet code), see:

    http://www.mvps.org/dmcritchie/excel/event.htm

    Macros must be enabled for this to work!