简体   繁体   中英

VBA How to add a loop with Application.WorksheetFunction.?

can you please advise how to loop my code through all populated rows (based on row D)? I need to subtract d2 from ad2, d3 from ad3 and so on and put the results in ae column (offset I guess).

Ideally, avoiding entering formulas in ae and instead using Application.WorksheetFunction.Value=Total ?

Sub valuedifference()
Dim Total As Double
Dim TimeX As Date
Dim TimeY As Date

With ThisWorkbook.Sheets("Test1")
TimeX = CDate(Range("d2").Value)
TimeY = CDate(Range("ad2").Value)
Total = TimeValue(TimeY) - TimeValue(TimeX)

Range("ag2").Value = Abs(Total * 24)
Range("ah2").Value = Abs(Total * 1440)
End With

End Sub

The following macro uses Column D to find the last row, and then loops through each row and places the results in Column AE...

Sub valuedifference()

    Dim Total As Double
    Dim TimeX As Date
    Dim TimeY As Date
    Dim LastRow As Long
    Dim i As Long
    
    With ThisWorkbook.Sheets("Test1")
        LastRow = .Cells(.Rows.Count, "d").End(xlUp).Row
        For i = 2 To LastRow
            TimeX = CDate(.Range("d" & i).Value)
            TimeY = CDate(.Range("ad" & i).Value)
            Total = DateDiff("n", TimeY, TimeX)
            .Range("AE" & i).Value = Total
            .Range("AG" & i).Value = Format(Abs(Total), "#.##")
            .Range("AH" & i).Value = Format(Abs(Total), "#.##")
        Next i
    End With

End Sub

I'd strongly recommend using Range variables and offsets rather than assembling cell name references.

Since the write back to the spreadsheet is a block of 3 cells, you can use an Array of the required values writing to the block to reduce spreadsheet updates.

One outstanding question for me is whether you want to capture the difference in days also, or just the time difference (regardless of date) as you do here?

Sub valuedifference()

Dim Total As Double
Dim TimeX As Date
Dim TimeY As Date
Dim LastD As Range
Dim DRange As Range
Dim ACell As Range

Set LastD = Sheets("Test1").Cells(Sheets("Test1").Cells.Rows.Count, 4).End(xlUp)
Set DRange = Range(Sheets("Test1").Range("D2"), LastD)
For Each ACell In DRange
    TimeX = CDate(ACell.Value)               ' from D column
    TimeY = CDate(ACell.Offset(0, 26).Value) ' from AD column
    Total = TimeValue(TimeY) - TimeValue(TimeX)
    ' Place results in AE rightward cells
    ACell.Offset(0, 27).Resize(1, 3).Value _
          = Array(Total, Abs(Total * 24), Abs(Total * 1440))
Next ACell

End Sub

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