隐藏选定单元格中的公式

问题描述

enter image description here

enter image description here

我的代码错误,它说 .formula = TheFormula(变量)没有设置。请帮我解决这个脚本。 我只想在单击单元格值时隐藏公式

     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

解决方法

使用以下代码。如果您选择“n4:o25”范围内的任何单元格,它将删除公式(仅保留值),但如果您选择其他内容,则它什么也不做。

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
,

您在 if 之后:

    Set Cell = ActiveCell

但是您的 else 部分缺少这一点。