简体   繁体   中英

Excel VBA: Max Date in the row including blank cells

Excel VBA: Code to find Max date in a row which includes blank cells

Dim s As Date

s = WorksheetFunction.Max((If IsNotEmpty (CDate(Range("A" & x + 1).Value), CDate(Range("B" & x + 2).Value), CDate(Range("C" & x + 1).Value)))
MsgBox s

I have a table in which there are around 8 colums containing dates (ex start date, end date etc). Now for each row, some of the columns are blank. I have to find the max date in each row.

enter image description here

Hello refer the below code for cell A1 to AA1 contains the date with blank cell also

Sub maxdaterow()
Max_date = Application.WorksheetFunction.Max(Range("A1:AA1"))
MsgBox Max_date
End Sub

below code to find the maximum date in column A, which also contains the blank cells

Sub maxdate()
Max_date = Application.WorksheetFunction.Max(Columns("A"))
MsgBox Max_date
End Sub

I would suggest you do this :

sub tryme()

For i = 1 To 50
    Max_date = Application.WorksheetFunction.Max(Rows(i))
    if isempty(Max_date) = False then
    MsgBox cDate("The most recent date for row : " & i & "is : " & Max_date)
    end if
Next
end sub

Where i is your row number; you will have to set your number of rows, or find it with .Count

You could try:

Option Explicit

Sub test()

    Dim i As Long, y As Long
    Dim dDate As Date

    With ThisWorkbook.Sheets("Sheet1")

        'Loop rows 1-10
        For i = 1 To 10
            'Set a default date
            dDate = "1/1/1900"
            'Loop columns from 1-8
            For y = 1 To 8
                If .Cells(i, y).Value <> "" And .Cells(i, y).Value > dDate Then
                    dDate = .Cells(i, y).Value
                End If
            Next y

            Debug.Print "Max date for row " & i & " is date " & dDate

        Next i

    End With

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