使用 VBA 在单元格中添加一天至今

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8156271/
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-08 12:10:54  来源:igfitidea点击:

Add one day to date in cells using VBA

excelvba

提问by Thad

I have a macro set up that will clear content on a spreadsheet. At the end of this Macro, I want to select specific cells that already have dates in them and then replace the current dates with current date +1. After searching the web I found the DateAdd function, but I am pretty new to VBA and I am having difficulty writing the function correctly. After selecting the necessary cells, how would I go about changing the dates to the next day?

我有一个宏设置,可以清除电子表格上的内容。在此宏的末尾,我想选择已包含日期的特定单元格,然后将当前日期替换为当前日期 +1。在网上搜索后,我找到了 DateAdd 函数,但我对 VBA 还很陌生,我很难正确编写该函数。选择必要的单元格后,我将如何将日期更改为第二天?

回答by Jean-Fran?ois Corbett

Taking your question literally, you could do this:

从字面上看你的问题,你可以这样做:

' Here goes the code where you select the date cells you want to increment
' ...
' Now increment them by 1 day:
Dim cell As Range
For Each cell In Selection
    cell.Value = cell.Value + 1 ' adds 1 day
Next cell

The unit of the Date data type is a day. So adding 1 adds one day.

Date 数据类型的单位是天。所以加1增加一天。

回答by Justin Self

Here's an example of how to use DateAdd:

以下是如何使用 DateAdd 的示例:

Range("A1").value = DateAdd("d", 1, CDate(Range("A1")))

This, of course, assumes a valid date is in A1. It will increment that date by a single day.

当然,这假定有效日期在 A1 中。它将将该日期增加一天。

"d" means we are adding a day. Here are the other intervals for adding years, months, etc.

“d”表示我们增加了一天。以下是添加年、月等的其他时间间隔。

yyyy - Year

yyyy - 年

q - Quarter

q - 季度

m - Month

米 - 月

y - Day of year

y - 一年中的第几天

d - Day

d - 天

w - Weekday

w - 工作日

ww - Week

ww - 周

h - Hour

h - 小时

n - Minute

n - 分钟

s - Second

s - 第二

Notice I use CDate. That simply converts the value of range("a1") into a date. It will throw an error if A1 cannot be parsed as a date.

注意我使用 CDate。这只是将 range("a1") 的值转换为日期。如果无法将 A1 解析为日期,则会引发错误。

Of course, you can also use this method to subtract days:

当然,你也可以用这个方法减去天数:

Range("A1").value = DateAdd("d", -3, CDate(Range("A1")))

This subtracts three days for the date in A1.

这将 A1 中的日期减去三天。

回答by yosukesabai

If you have date in cell a1 and want increment one day, it should be as simple as

如果您在单元格 a1 中有日期并希望增加一天,它应该像

range("a1").value = range("a1").value + 1

range("a1").value = range("a1").value + 1