簡體   English   中英

清除Excel中公式中使用的內容后的一個單元格

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

我正在嘗試創建一個場景,如果我要在一個單元格中輸入一個數字,我希望該數字用於另一個單元格公式,而不是我輸入數字的單元格在點擊回車后被清除。

示例:單元格 G2 具有公式=Sum(A2,B2)-C2

單元格 B2 是 10

單元格 C2 是 2

在單元格 A2 中輸入 7

點擊進入后,單元格 G2 應顯示 15,單元格 A2 應被清除。

到目前為止,我只能讓單元格清除:

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

我正在嘗試將Application.Evaluate("Sum(A2, B2) - C2")用於公式,但我無法讓它們協同工作。

這可能嗎?

感謝您的幫助。

工作表更改:評估公式

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