用于根据另一个单元格的值插入特定日期的宏

发布于 2025-01-19 08:35:43 字数 111 浏览 0 评论 0原文

我有一个带有数字和字母的单元格。例如:06052022_GST_402。在此示例中,“ 06052022”部分是特定日期(2022年6月5日)。我希望宏可以识别该值的日期,并以6/5/2022的格式输入日期。

I have a cell with a string of numbers and letters. For example: 06052022_GST_402. In this example, the "06052022" part is a specific date (June 5, 2022). I want the macro to recognize the date from that value and enter the date in format 6/5/2022 into another cell.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

王权女流氓 2025-01-26 08:35:43

这是您可以实现这一目标的一种方法:

'Split the string by underscore delimiter into array and grab the first element (this will be string '06052022')
string_date = Split("06052022_GST_402", "_")(0)

'From that string grab each date component and store in a variable
string_year = Right(string_date, 4)
string_month = Mid(string_date, 3, 2)
string_day = Left(string_date, 2)

'Using function `DateValue()` concatenate the string date parts into a date of format `MM/DD/YYYY` which DateValue will turn into an actual date. Store that actual date in variable date_date and do with it as you wish. 
date_date = DateValue(string_month & "/" & string_day & "/" & string_year)

'Stick that date in a cell
Worksheets("Sheet1").Range("A1").value = date_date

您也可以一对一地完成这一丑闻:

x="06052022_GST_402"
Worksheets("Sheet1").Range("A1").value = Mid(x, 3, 2) & "/" & Left(x, 2) & "/" & Mid(x, 5, 4)

但是,这将吐出日期的字符串表示,而不是实际的日期 type ,因此它可以行动在您的工作表中愚蠢,并带有任何期望约会的下游功能。

Here's a way you can pull this off:

'Split the string by underscore delimiter into array and grab the first element (this will be string '06052022')
string_date = Split("06052022_GST_402", "_")(0)

'From that string grab each date component and store in a variable
string_year = Right(string_date, 4)
string_month = Mid(string_date, 3, 2)
string_day = Left(string_date, 2)

'Using function `DateValue()` concatenate the string date parts into a date of format `MM/DD/YYYY` which DateValue will turn into an actual date. Store that actual date in variable date_date and do with it as you wish. 
date_date = DateValue(string_month & "/" & string_day & "/" & string_year)

'Stick that date in a cell
Worksheets("Sheet1").Range("A1").value = date_date

You could do this one in one ugly line too:

x="06052022_GST_402"
Worksheets("Sheet1").Range("A1").value = Mid(x, 3, 2) & "/" & Left(x, 2) & "/" & Mid(x, 5, 4)

But that's going to spit out a string representation of the date, not an actual date type and so it may act goofy in your sheet with any downstream functions that are expecting a date.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文