Excel 儲存格公式

Excel 儲存格公式

我需要一個Excel中的公式,將單元格A1的值複製並顯示到B1,如果單元格A1的值從正值更改為零,則單元格B1中的值不得更改,它必須保留其先前的值(即始終大於零)。值是數字。

答案1

這不能只用公式來完成。但下面的 VBA 程式碼是基於選擇更改事件, 有用:

Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
    Const SourceCell = "$A$1"
    Const TargetCell = "$A$2"

    If Target.Address = SourceCell Then
        If Range(SourceCell).Value > 0 Then
            Range(TargetCell).Value = Range(SourceCell).Value
        End If
    End If
End Sub

或者,如果您想要更多來源和目標儲存格(按稍後的要求):

Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
    Dim SourceCells(), TargetCells() As Variant
    Dim i As Integer

    ' Make sure the cells are declared with $'s
    ' Make sure that the arrays contain the same number of elements
    SourceCells = Array("$B$1", "$B$2", "$F$5")
    TargetCells = Array("$A$1", "$A$2", "$H$12")

    For i = 0 To UBound(SourceCells)
        If Target.Address = SourceCells(i) Then
            If Range(SourceCells(i)).Value > 0 Then
                Range(TargetCells(i)).Value = Range(SourceCells(i)).Value
            End If
        End If
    Next i

End Sub

將此程式碼放入 VBA 程式碼中工作表您希望在哪裡完成此操作。為此,請按照以下說明操作:

  • 在 Excel 中,開啟工作簿,按一下ALT+ F11。這將開啟 VBA 編輯器。
  • 檢查左側的「項目」樹,然後找到 Excel 工作簿和工作表。右鍵單擊(用滑鼠)該工作表並選擇View Code
  • 將上面的程式碼複製並貼上到編輯器中。
  • 關閉 VBA 編輯器,一切都應該按預期工作。

相關內容