表格和文本框中的dateExcel VBA错误

我住在澳大利亚,我们使用d / mm / yyyydate格式。 我想在excel中用VBA制作一个用户窗体,它将读取一个单元格(A1),并将其显示在文本框中。 用户可以在另一个文本框中inputdate,并将该date设置回单元格(A1)。 我的问题是,当我正在阅读单元格(A1)的date是从文本框中的d / mm / yyyy更改为m / dd / yyyy。 我已经使用了“=格式(DateCurrent_Tbx.Value,”d / mmm / yy“)”,但没有区别。 我在Windows 7 SP1 64位计算机上使用Excel 2010 32位,并将计算机设置为英文(澳大利亚)时间格式。 单元格(A1)设置为自定义格式“d / mm / yyyy”

由于我使用的文件的VBA代码是非常长的,我已经在一个较小的用户表单(附加的Excel文件)中复制了错误。

带有错误的Excel文件示例

Private Sub LockInput_Cmd_Click() SetDate_Cmd.Caption = InputDate_Tbx.Value SetDate_Cmd.Caption = Format(SetDate_Cmd.Caption, "d/mmm/yy") End Sub Private Sub SetDate_Cmd_Click() ThisWorkbook.Sheets(1).Range("A1").Value = SetDate_Cmd.Caption DateCurrent_Tbx.Value = ThisWorkbook.Sheets(1).Range("A1").Value DateCurrent_Tbx.Value = Format(DateCurrent_Tbx.Value, "d/mmm/yy") End Sub Private Sub UserForm_Initialize() DateCurrent_Tbx.Value = ThisWorkbook.Sheets(1).Range("A1").Value DateCurrent_Tbx.Value = Format(DateCurrent_Tbx.Value, "d/mmm/yy") End Sub 

我一直绞着脑袋在网上search了好几天没有用。 我希望我已经清楚地解释了一些事情。

对于看起来像date和实际date的string存在一些混淆,而以EN-US为中心的VBA默认MDY语言环境没有采取任何措施来缓解这种情况。

首先,A1中的date是0到42,225之间的一个数字(2015年8月9日是42,225); 没有更多或更less。 无论您的计算机系统运行在哪个区域,您都可以将其打扮成d / mm / yyyy。 我在EN-US下运行,如果我使用d / mm / yyyy的数字格式掩码,则显示date为2015年9月8日时没有问题。 要将显示的date从A1返回到文本框AS A STRING,请使用Range.Text属性 。 这是在单元格中显示的文本。 它是只读的,所以你不能填入“9/08/2015”string。

 Private Sub UserForm_Initialize() DateCurrent_Tbx.Value = ThisWorkbook.Sheets(1).Range("A1").TEXT End Sub 

就用户input“字符看起来像一个date”而言,你可能不得不相信你的用户做一些正确的事情。 如果可以依靠它们以DMY格式input,则可以使用DateSerial函数将这些部分拆分并正确放置在一起。

 Private Sub LockInput_Cmd_Click() dim dt as date, vDT as variant vDT = split(InputDate_Tbx.Value, chr(47)) 'split the string-date on the forward slash dt = DateSerial(vDT(2), vDT(1), vDT(0)) 'create a real date SetDate_Cmd.Caption = Format(dt, "d/mmm/yy") 'use any format mask you want to create another string-date End Sub Private Sub SetDate_Cmd_Click() dim dt as date, vDT as variant vDT = split(SetDate_Cmd.Caption, chr(47)) 'split the string-date on the forward slash dt = DateSerial(vDT(2), vDT(1), vDT(0)) 'create a real date ThisWorkbook.Sheets(1).Range("A1").Value = dt 'put the actual date back into A1 End Sub 

就CDatefunction而言,我会避免使用它。 如果你把“19/08/2015”填入CDate(在VBE的立即窗口中作为?CDate("19/08/2015") ),它将正确解释为2015年8月19日,但这只是因为IT没有其他select! 如果您尝试使用相同的?CDate("9/08/2015") 2015年9月8日?CDate("9/08/2015") ,则最终会出现在2015年9月8日,因为只要有select,CDate就会selectMDY的EN-US语言环境。 最好不要依赖这个。 我相信DateValue函数至less是不可靠的。