格式在Excel中dynamic添加文本框

我在用户窗体中dynamic添加TextBox,并希望使它们成为date格式以确保input正确的date。 我无法find任何例子。

这是我的代码为用户表单激活:

Private Sub TextBox3_Exit(ByVal Cancel As MSForms.ReturnBoolean) fltDays = TextBox3.Value If TextBox3.Value = 0 Then Exit Sub For i = 1 To fltDays n = i - 1 Dim TextBox As Control Set theLbl = FloatDayFrm.Controls.add("Forms.Label.1", "lbl_" & i, True) With theLbl .Caption = "Day " & i .Left = 20 .Width = 60 .Top = n * 24 + 100 .Font.Size = 10 End With Set TextBox = FloatDayFrm.Controls.add("Forms.TextBox.1", "TextBox_" & n, True) With TextBox .Top = 100 + (n * 24) .Left = 90 .Height = 18 .Width = 50 .Name = "txtBox" & i .Font.Size = 10 .TabIndex = n + 4 .TabStop = True End With Next i FloatDayFrm.Height = 150 + fltDays * 24 With btnOK .Top = 102 + fltDays * 24 .TabStop = True .TabIndex = n + 5 End With With btnCancel .Top = 102 + fltDays * 24 '.TabStop = True .TabIndex = n + 6 End With End Sub 

这是我的命令button的代码:

 Private Sub btnOK_Click() n = TextBox3.Value For j = 1 To n Set varFloatDay = FloatDayFrm.Controls("txtBox" & j) Select Case varFloatDay Case "" MsgBox "Day " & j & " can't be blank", vbOKOnly, "Incorrect Value" Exit Sub Case Is > TextBox2.Value MsgBox "Date is after end date", vbOKOnly, "Incorrect Value" Exit Sub Case Is < TextBox1.Value MsgBox "Date is BEFORE end date", vbOKOnly, "Incorrect Value" Exit Sub End Select Next j End Sub 

任何帮助,将不胜感激。

您必须将文本转换为date格式。 你可以使用多种方法。

  1. 在文本框旁边添加标签以显示用户必须指定date的格式。 按照格式parsing用户指定的文本。 进行validation和转换,如下面的代码所示。
  2. 使用日历控件而不是文本框作为用户input。
  3. 有单独的文本框或单元格的年,月和日。 进行validation和转换,如下面的代码所示。
  4. 如果您确定date是按照区域设置指定的格式。 进行validation和转换,如下面的代码所示。

尝试下面

 Private Sub TestDate() Dim yr As Integer Dim mnth As Integer Dim day As Integer Dim dt As Date Dim strDate As String '''''3rd approach'''''' yr = ActiveSheet.Range("A1") mnth = ActiveSheet.Range("B1") day = ActiveSheet.Range("C1") If IsNumeric(yr) And IsNumeric(mnth) And IsNumeric(day) Then If yr < 0 Or mnth < 0 Or day < 0 Then MsgBox "Year, Month and Day must be greater than 0." Exit Sub End If Else MsgBox "Year, Month and Day must be an integer." Exit Sub End If 'convert to Date dt = DateSerial(yr, mnth, day) '''''4th approach'''''' 'Display a date according to your system's short date format 'ie regional settings in control panel strDate = Format(ActiveSheet.Range("D1"), "Short Date") If Not IsDate(strDate) Then MsgBox "Incorrect Date Format" Exit Sub End If dt = CDate(strDate) End Sub 

文本框中的任何input都是文本string。 如果您希望它是一个date,您可以使用IsDate(TextBox1.Value)来确定VBA是否能够将string转换为date(这是一个Doubletypes的数字)。 然而,VBA不会正确执行这个testing。 例如,如果您的区域设置将date分隔符作为句点,则可能不会将3/2/17识别为date。 如果您的区域设置是mm.dd.yy,它可能会将3.2.17转换为3月2日。 在您自己的PC上工作时,您可能能够控制区域设置。 但是,如果您的项目将被释放到野外,最好使用日历控件来获取正确的date。