简体   繁体   中英

Applying date validation to Excel cell from VB.Net

I am working on applying date validation to excel cell(range) from VB.NET.

 Private Sub DateValidExcelRule(ByVal worksheet As SpreadsheetGear.IWorksheet, ByVal DateRange As String)

    Dim dt As Date = CDate("1/1/1900")
    worksheet.Range(DateRange).Validation.Delete()
    worksheet.Range(DateRange).Validation.Add(ValidationType.Date, ValidationAlertStyle.Stop, ValidationOperator.Greater, dt, Nothing)
    worksheet.Range(DateRange).NumberFormat = "mm/dd/yyyy"
    worksheet.Range(DateRange).Validation.IgnoreBlank = True
    worksheet.Range(DateRange).Validation.InputTitle = "Excel Validation"
    worksheet.Range(DateRange).Validation.ErrorTitle = "Error in Date"
    worksheet.Range(DateRange).Validation.InputMessage = "Note: only date values here"
    worksheet.Range(DateRange).Validation.ErrorMessage = "Enter valid Date"
    worksheet.Range(DateRange).Validation.ShowInputMessage = True
    worksheet.Range(DateRange).Validation.ShowError = True

End Sub

Problem:

When I enter 4 digits whole number 7777 it is validating correctly showing message Enter Valid Date , but when I enter 5 digits 77777 it is accepting the value and converting it to 12/10/2112 value and not showing any error message.

Here all I want to do is I want to validate the cell value to any date format mm/dd/yyyy .

Please let me know, am I going in the right way?

Excel stores dates as serial dates (the number of days since 1/0/1900), so if you take 77777 days and add it to that date it starts you get a valid date. 12/10/2112

I am not sure how or even if you can accomplish exactly what you want forcing the input to be in that specific format in excel. (Without using a date control) But that is the why at least.

Here are a couple links I have found to be useful with dates/times in excel.

http://www.cpearson.com/excel/datetime.htm

http://dmcritchie.mvps.org/excel/datetime.htm

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