Home > Back-end >  subtract a range of cells to a single cell
subtract a range of cells to a single cell

Time:09-17

In my VBA code below it takes a start number in cell d1 takes another number in cell b5 then displays the result in cell d7. What I want to do is take a range of cells that subtract from the cell in d1. So right now it just takes cell b5 values. I want the range to go from b5-f5. So all of the cells in that range should subtract from cell d1 then the output is displayed in d7.

Sub Preform_Subtraction_Verion1()
    
    Dim CalcWS As Worksheet
    Dim StartingTotal As Double
    Dim DayTotal As Double
    
    Set CalcWS = ThisWorkbook.Worksheets("Sheet1")
    
    With CalcWS
        StartingTotal = .Range("D1").Value
        DayTotal = .Range("B5").Value
        .Range("D7").Value = StartingTotal - DayTotal
    End With
    
End Sub

CodePudding user response:

Like this? Or do you need a separate output from each cell in range("B5:F5")?

Option Explicit
Sub Preform_Subtraction_Verion1()
    
    Dim CalcWS As Worksheet
    Dim StartingTotal As Double
    Dim DayTotal As Double
    
    Set CalcWS = ThisWorkbook.Worksheets("Sheet1")
    
    With CalcWS
        StartingTotal = .Range("D1").Value
        DayTotal = Application.WorksheetFunction.Sum(.Range("B5:F5"))
        .Range("D7").Value = StartingTotal - DayTotal
    End With
    
End Sub

Example

  • Related