Search code examples
excelvbaobjecteventshide

Hiding the formula in the selected cell


enter image description here

enter image description here

I am having error in my code, it says in .formula = TheFormula (variable) is not set. Please help me to resolve this script. I just want to hide the formula when I clicked the cell value.

     Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        Dim Rng As Range
        Static Cell As Range
        Static TheFormula As String
        Set Rng = Range("n4:o25")
         If Not Application.Intersect(Target, Rng) Is Nothing Then
          If Not Cell Is Nothing Then
            Cell.Formula = TheFormula
          End If
         Set Cell = ActiveCell
        With Cell
         TheFormula = .Formula
          .Value = .Value
        End With
       Else
        With Cell
        .Formula = TheFormula
        End With
       End If
   End Sub

Solution

  • Use the following code. It removes the formula (keeps only the value) if you select any cell in range "n4:o25", but if you select something else it does nothing.

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim Rng As Range
    Static Cell As Range
    Set Rng = Range("n4:o25")
      If Not Application.Intersect(Target, Rng) Is Nothing Then
        Set Cell = ActiveCell
        If Not Cell Is Nothing Then
          Cell.Value = Cell.Value
        End If
      End If
    End Sub