vba 获取一个月内的第一个和最后一个日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17324722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 21:53:25  来源:igfitidea点击:

Getting the first and last dates in a month

vbams-access

提问by Jason Bayldon

I have two comboboxes that lets the user select a date and year. What I want to do is to translate this into my query in access, which requires a [start date] and an [end date] parameter.

我有两个组合框,可让用户选择日期和年份。我想要做的是将其转换为访问中的查询,这需要 [开始日期] 和 [结束日期] 参数。

I.E. user picks "May" and "2013" in the combo boxes

IE 用户在组合框中选择“May”和“2013”

My query is setup between [start date] and [end date], so I want to translate this month and year selection from the combo boxes into two strings (startdate and enddate, then pass them as command parameters) that contain MM/DD/YYYY, MM/DD/YYYY. What is the best way to take two strings and get the first valid day and last valid day. I have:

我的查询设置在 [开始日期] 和 [结束日期] 之间,所以我想将组合框中的月份和年份选择转换为包含 MM/DD/ 的两个字符串(开始日期和结束日期,然后将它们作为命令参数传递) YYYY、MM/DD/YYYY。获取两个字符串并获得第一个有效日和最后一个有效日的最佳方法是什么。我有:

FirstDayInMonth = DateSerial( _
 Year(Date), Month(Date), 1)

LastDayInMonth = DateSerial( _
 Year(dtmDate), Month(dtmDate) + 1, 0)

But I need to make the switch from a string into a date format to get back the first/last day of the selected month, using only the month ("MAY") and year ("2013")? Am I missing something relatively simple?

但是我需要从字符串转换为日期格式以返回所选月份的第一天/最后一天,仅使用月份(“MAY”)和年份(“2013”​​)?我错过了一些相对简单的东西吗?

回答by Gord Thompson

Make the "Month" combo box have two columns (Column Countproperty is 2):

使“月份”组合框有两列(Column Count属性为2):

 1 | Jan
 2 | Feb
...
12 | Dec

Set the Bound Columnof the combo box to 1so its .Valueis the month number, but display only the month name (hide the number) by setting the width of the first column to zero:

Bound Column组合框的 设置为1因此它.Value是月份数,但通过将第一列的宽度设置为零来仅显示月份名称(隐藏数字):

Column Widths: 0";0.75"

回答by KekuSemau

So, do you get the month and year (as integer or long, not a date yet) from the comboboxes?
Then try this:

那么,您是否从组合框中获得了月份和年份(作为整数或长,还不是日期)?
然后试试这个:

Dim m As Long
Dim y As Long
Dim d_from As Date
Dim d_until As Date

m = CLng("01") ' get these two from your comboboxes
y = CLng("2013") 
d_from = DateSerial(y, m, 1)

d_until = DateAdd("m", 1, d_from)
d_until = DateAdd("d", -1, d_until)

When you have the first date, you calculate the second (last day in month) by adding one month, then going one day back.

当您有第一个日期时,您通过添加一个月然后返回一天来计算第二个(一个月中的最后一天)。