简体   繁体   中英

Subtraction of Dates using macros

In myexcel I wanted to calculate the difference in days between a Single Date in a cell and a series of Dates in column AS2:AS400

Also the difference in days i want it in a seperate column.

I tried to understand the code via record macro and modify it to a two line code. But I couldnt not make it. Could anyone simplyfy the below code to simplfied program. So that I can use for a large no. of data very easily in a column instead of writing it for every single cell.

Range("AS2").Select
ActiveCell.FormulaR1C1 = "=R[3]C[-42]-RC[-22]"
Range("AS3").Select
ActiveCell.FormulaR1C1 = "=R[2]C[-42]-RC[-22]"
Range("AS4").Select
ActiveCell.FormulaR1C1 = "=R[1]C[-42]-RC[-22]"
Range("AS5").Select
ActiveCell.FormulaR1C1 = "=RC[-42]-RC[-22]"
Range("AS6").Select
ActiveCell.FormulaR1C1 = "=R[-1]C[-42]-RC[-22]"
Range("AS7").Select
ActiveCell.FormulaR1C1 = "=R[-2]C[-42]-RC[-22]"
Range("AS8").Select
ActiveCell.FormulaR1C1 = "=R[-3]C[-42]-RC[-22]"   

Have a look at the documentation of the DateDiff Function :

For example:

Range("BA2").Value = DateDiff("d", Range("C5").Value,  Range("AS2").Value)

… will return the difference of C5 and AS2 in days into BA2.


But you can do that without VBA too:

Put the following formula into BA2 =DAYS(C5,AS2) to get the difference in days.


Or you can write that formula with VBA into the cell:

Range("BA2").Formula = "=DAYS(C5,AS2)"

For writing multiple formulas in a loop:

Dim i As Long
For i = 2 to 5
    Range("BA" & i).Formula = "=DAYS(C5,AS" & i &")"
Next i

Or even better just write the first cell and copy it down

Range("BA2").Formula = "=DAYS($C$5,AS2)" 'write first formula
Range("BA2").AutoFill Destination:=Range("BA2:BA5"), Type:=xlFillDefault 'copy it down until BA5

Note that $C$5 is a fixed cell but AS2 will adjust dynamically when you copy down.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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