日期格式的组合框

时间:2017-05-24 16:54:10

标签: excel vba

我的用户表单有三个单独的组合框供用户选择以下内容:年,月,日(它们不依赖)。例如,如果用户选择2017(年份),5月(月份)和23(当天),我希望vba在我的数据库表格的第二列中输入:" 2017/05/23"。我希望它完全以这种格式作为值。

以下代码不起作用。任何帮助,将不胜感激。

 With ws
 .Cells(lRow, 2).Value = Me.cboYear / Me.cboMonth / Me.cboDay.Value
 End With

1 个答案:

答案 0 :(得分:3)

您将年份除以月份,然后除以该日期。这就是你的细胞获得的价值。

建立一个实际的日期

SELECT ID, Type, ValueA
FROM TABLE
GROUP BY ID, Type, ValueA
HAVING COUNT(ID) > 1
ORDER BY ID, Type, ValueA

然后使用.Cells(lRow, 2).Value = DateSerial(cboYear, cboMonth, cboDay)

以任意方式格式化该日期
NumberFormat

.Cells(lRow, 2).NumberFormat = "yyyy/MM/dd" 需要整数值。如果你的DateSerial包含字符串(月份名称),那么你需要更努力地工作 - 最简单的可能只是使用一个键控集合 - 在cboMonth整数时指定一个字符串键集合:

.Add

然后你可以轻松查找:

Static months As Collection
If months Is Nothing Then
    Set months = New Collection
    With months
        .Add 1, "January"
        .Add 2, "February"
        .Add 3, "March"
        '...
        .Add 12, "December"
    End With        
End If

所以你的Dim monthId As Integer monthId = months(cboMonth) 会是:

DateSerial
相关问题