简体   繁体   English

清除Excel中公式中使用的内容后的一个单元格

[英]Clear a cell in Excel after contents used in formula

I am trying to create a scenario where if I am to enter a number into a cell, I want that number to be used in another cells formula and than the cell I entered the number in to be cleared after hitting enter.我正在尝试创建一个场景,如果我要在一个单元格中输入一个数字,我希望该数字用于另一个单元格公式,而不是我输入数字的单元格在点击回车后被清除。

Example: Cell G2 has formula =Sum(A2,B2)-C2示例:单元格 G2 具有公式=Sum(A2,B2)-C2

Cell B2 is 10单元格 B2 是 10

Cell C2 is 2单元格 C2 是 2

Enter 7 into cell A2在单元格 A2 中输入 7

After hitting enter Cell G2 should show 15 and Cell A2 should be cleared.点击进入后,单元格 G2 应显示 15,单元格 A2 应被清除。

So far I am only able to get the cell to clear:到目前为止,我只能让单元格清除:

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False
        Target.ClearContents
    Application.EnableEvents = True
End Sub

I am trying to use Application.Evaluate("Sum(A2, B2) - C2") for the formula but I cannot get them to work together.我正在尝试将Application.Evaluate("Sum(A2, B2) - C2")用于公式,但我无法让它们协同工作。

Is this possible?这可能吗?

Thank you for any assistance.感谢您的帮助。

A Worksheet Change: Evaluate a Formula工作表更改:评估公式

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    
    Const FirstCellAddress As String = "A2"
    Const FormulaColumn As String = "G"
    
    Dim irg As Range
    With Me.Range(FirstCellAddress)
        Set irg = Intersect(.Resize(Me.Rows.Count - .Row + 1), Target)
    End With
    If irg Is Nothing Then Exit Sub
    
    Application.EnableEvents = False
    
    With irg
        Intersect(.EntireRow, Me.Columns(FormulaColumn)).Value _
            = Me.Evaluate(.Cells(1).Address & "+" & .Cells(1) _
            .Offset(, 1).Address & "-" & .Cells(1).Offset(, 2).Address)
        .ClearContents
    End With
    
    Application.EnableEvents = True

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM