Vb.net 用VB在Excel表格中输入日期。如果输入的日期小于12,则日期格式会更改

Vb.net 用VB在Excel表格中输入日期。如果输入的日期小于12,则日期格式会更改,vb.net,Vb.net,这是我的代码: 'HomeP form has the excelapp, excelwb, excelws objects initialized. HomeP.excelws.Range("C1", "C900000").NumberFormat = "dd-MMM-yyyy" HomeP.excelws.Range("D1", "D900000").NumberFormat = "dd-MMM-yyyy" 我正在使用文本框进行输入 HomeP.excelws.Cells(2, 3).V

这是我的代码:

'HomeP form has the excelapp, excelwb, excelws objects initialized.

HomeP.excelws.Range("C1", "C900000").NumberFormat = "dd-MMM-yyyy"
HomeP.excelws.Range("D1", "D900000").NumberFormat = "dd-MMM-yyyy"
我正在使用文本框进行输入

HomeP.excelws.Cells(2, 3).Value = TextBox3.Text
HomeP.excelws.Cells(2, 4).Value = TextBox4.Text
[编辑]:现在的问题是,如果我输入'23-12-2001',它将在excel中存储为'23-Dec-2001',但如果我输入'01-11-2001',它将存储为'11-Jan-2001'。我不认为这与输入有关,而是当一天少于12天时Excel如何解释它。我的系统日期格式为dd mm yyyy。我希望excel单元格中的日期格式为“dd-MMM-yyyy”

我想您可以尝试:

        Dim Timee As DateTime = HomeP.excelws.Cells(2, 3).Value
        Dim Formatt As String = "dd-MM-yyyy"
        Dim newdate = Timee.ToString(Formatt)
        TextBox3.Text = newdate

请告诉我它是否有效

多亏了TnTinMin和Aladein,问题解决了。我创建此方法是为了以所需格式获取日期

    Public Function GetDateProperly(ByVal tb As TextBox)
    Try
        Dim timee As DateTime = tb.Text
        Dim Formatt As String = "dd-MMM-yyyy"
        Dim newdate = timee.ToString(Formatt)
        Return CDate(newdate)
    Catch ex As System.InvalidCastException
    Catch ex As NullReferenceException
    End Try
    End Function

PS-我正在使用MS Excel 2010和Visual Studio 2015进行编码。如果
TextBox3.Text
表示的值应该是
DateTime
,则将该字符串解析为
DateTime
变量,并将该变量分配给
Excel.Range.value
属性。这样做可以消除所有歧义。请尝试。仍然没有成功。查看下面答案中的评论。:)<代码>试过了。仍然没有成功。-->
Dim timee As DateTime=TextBox3.Text Dim format As String=“dd MM yyy”Dim newdate=timee.ToString(format)HomeP.excells.Cells(2,3)。Value=newdate
。这不是我的建议。您仍在分配字符串。试试:
HomeP.excells.Cells(2,3).Value=CDate(TextBox3.Text)
非常感谢。这对我起了作用:)对不起,我的坏消息没有正确地跟随你,新手。Dim timee As DateTime=TextBox3.Text Dim format As String=“dd MM yyyy”Dim newdate=timee.ToString(format)HomeP.excells.Cells(2,3)。Value=newdate尝试过这个,仍然一样。我认为问题不在于输入,而在于excel如何解释输入。当输入的日期少于12天时,它会自动更改格式。它不会将日期格式从dd-mm-yyyy更改为mm-dd-yyyy。它以不同的方式解释它。例如,我输入了2017年1月12日,它作为2017年1月12日保存在excel中。