date格式的combobox
我的用户表单有三个独立的combobox供用户select以下内容:年,月,日(不依赖于)。 例如,如果用户select2017(年),5月(月)和23(当天),我希望vba在我的数据库表格第二栏中input:“2017/05/23”。 我想正是以这种格式作为价值。
下面的代码不起作用。 任何帮助,将不胜感激。
With ws .Cells(lRow, 2).Value = Me.cboYear / Me.cboMonth / Me.cboDay.Value End With
你把这一年除以一个月,然后再除以一天。 这是你的细胞正在获得的价值。
build立一个实际的date 。
.Cells(lRow, 2).Value = DateSerial(cboYear, cboMonth, cboDay)
然后使用NumberFormat
任何方式格式化该date:
.Cells(lRow, 2).NumberFormat = "yyyy/MM/dd"
DateSerial
需要整数值。 如果您的cboMonth
包含string(月份名称),那么您需要更加努力 – 最简单的方法是使用键控集合 – 在添加整数到集合时指定string键:
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
将是:
.Cells(lRow, 2).Value = DateSerial(cboYear, monthId, cboDay)