简体   繁体   English

如何使用vba将yyyymm数字字符串转换为结束月份日期?

[英]how to convert yyyymm number string into end month date using vba?

Currently, in my Excel, there is a string of year and month written as yyyymm. 目前,在我的Excel中,有一个年份和月份的字符串写为yyyymm。 Eg: 201706 例如:201706

Right now I would like to convert it into the end of month date in another worksheet. 现在我想在另一个工作表中将其转换为月末日期。 Eg: 20170630 例如:20170630

The question now is, how do I tell Excel to auto create the day based on the month value in the string? 现在的问题是,如何告诉Excel根据字符串中的月份值自动创建日期?

I was planning on using if statements to declare each month based on the ending value at the back of the string. 我打算使用if语句根据字符串后面的结束值声明每个月。 (ie: If 2017 06 , date = 20170630) (即:如果2017年06月,日期= 20170630)

But then I thought that won't work for February's leap year. 但后来我认为这对2月份的闰年不起作用。 Is there another method to use besides that? 除此之外还有其他方法吗?

Try this 尝试这个

dtmDate = 201706 (or put there value from cell)

dhLastDayInMonth = DateSerial(Left(dtmDate, 4), Right(dtmDate, 2) + 1, 0)

The easiest way to solve your problem is to not even use a vba makro. 解决问题的最简单方法是不使用vb​​a makro。 Using the Date , Left and Right as well as EOMonth functions you can sinply convert your string to a date like in the example below. 使用DateLeftRight以及EOMonth函数,您可以将字符串转换为如下例所示的日期。

Using this you don't even need vba: 使用这个你甚至不需要vba:

=EOMONTH(DATE(LEFT(A1;4);RIGHT(A1;2);1);0) (example if date string is in A1) =EOMONTH(DATE(LEFT(A1;4);RIGHT(A1;2);1);0) (例如,如果日期字符串在A1中)

Check out this page to get more detail on this function 查看页面以获取有关此功能的更多详细信息

I often use a little workaround by taking the first day of the following month (which is always the 1st) and subtract 1 of the date. 我经常使用下一个月的第一天(始终是第一天)并减去日期的1来进行一些解决方法。 Unfortunately that only works with Date-Values: 不幸的是,它只适用于Date-Values:

Try this one: 试试这个:

Sub LastDayOfMonth()

    strInput = "201711"
    y = Left(strInput, 4)
    m = Right(strInput, 2)

    dat = DateSerial(y, m + 1, 1) - 1

End Sub
Dim dLast As Date
 dLast = DateAdd("d", -1, CDate("1/" & Format(Date, "mm/yyyy")))

Or through a messageBox if you put the date in cell A1: 或者如果您将日期放在单元格A1中,则通过messageBox:

MsgBox Format([eomonth(A1,6)], "dd/mm/yyyy")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM