首页 > 解决方案 > 在单元格中输入日期

问题描述

我有一个按钮,单击该按钮时将在文本框中给出当前日期和时间。然后我使用另一个程序将其移动到单元格中。但这在我双击它之前不被视为日期。在过滤期间,这个输入的日期被排除在其他日期之外

我已经完成了日期的格式化(ddmmyy HHmm)

Private Sub CommandButton5_Click()



If Not TextBox6.Value = "" Then

ans = msgbox(" Date already exits.Do you want to continue", vbYesNo + vbQuestion)



If ans = vbYes Then

TextBox6.Value = Format(Now(), ddmmyyHHmm)

End If

End If


If TextBox6.Value = "" Then


TextBox6.Value = Format(Now(), ddmmyyHHmm)

End If



End Sub

并将值复制到单元格,我使用了 cells(i,"A").value = textbox6.value

标签: excelvba

解决方案


Format返回一个Variant/String。您想在单元格中输入实际日期/时间,而不是 Excel 不再将其识别为日期的格式化日期/时间。

一种选择是使用DateSerialTimeSerial从该字符串建立一个真实的日期/时间。虽然可能有一种更简单的方法来实现这一点,但无论如何,这里有一个例子:

Dim x As String
x = TextBox6.Value

Dim yy As Integer, dd As Integer, mm As Integer, hh As Integer, min As Integer
yy = CInt(Mid(x, 5, 2)) ' year
mm = CInt(Mid(x, 3, 2)) ' month
dd = CInt(Mid(x, 1, 2)) ' day
hh = CInt(Mid(x, 7, 2)) ' hour
min = CInt(Mid(x, 9, 2)) ' minute

Cells(i, "A").Value = DateSerial(yy, mm, dd) + TimeSerial(hh, min, 0)

如果要使用该日期/时间格式设置单元格:

Cells(i, "A").NumberFormat = "ddmmyyHHmm"

推荐阅读