使用VBA来检查一个单元格是否包含一个date,如果是这样,则提前一个月

我有一列数据(C)有很多包含date的单元格。 我试图创build一个macros来检查每个单元格是否包含一个date,如果它确实然后推进月份的date。 我有代码来提前一个月的date从这里http://excel.tips.net/T002180_Automatically_Advancing_by_a_Month.html它工作正常,但我不知道如何replace范围与一个dynamic范围,评估C列中的所有单元格如果可能的话,我也想消除循环的需要。 这是我迄今为止。

Sub IncreaseMonth() Dim dDate As Date Dim NumberofTasks As Integer NumberofTasks = ThisWorkbook.Worksheets("Dashboard").Range("Number_of_Tasks") Dim x As Integer For x = 1 To NumberofTasks dDate = Range("C30").Value Range("C30").Value = _ DateSerial(Year(dDate), _ Month(dDate) + 1, Day(dDate)) Next x End Sub 

尝试像下面的代码(我使用DateAdd函数添加1个月的当前date值)

 Sub IncreaseMonth() Dim dDate As Date Dim NumberofTasks As Long Dim x As Long With Worksheets("Dashboard") ' I suspect you want to get the last row with data in Column C NumberofTasks = .Cells(.Rows.Count, "C").End(xlUp).Row For x = 1 To NumberofTasks If IsDate(.Range("C" & x).Value) Then '<-- check if current cell at Column C is Date .Range("C" & x).Value = DateAdd("m", 1, .Range("C" & x).Value) '<-- add 1 Month to current date in Column c, use DateAdd function End If Next x End With End Sub 

这段代码应该把你放在正确的轨道上。 我在这里做了一些假设。 首先是您有一个名为“Number_of_Tasks”的命名范围,您希望在其中进行操作。 其次,这个范围内的所有值都是有效的date。 如果值可能是无效date(如空白),则应在设置值之前检查此值。

你也希望确保这个月不会失效。 递增十二月份的月份不会是有效的date。

 Sub IncreaseMonth() Dim tempCell As Range For Each tempCell In ThisWorkbook.Worksheets("Dashboard").Range("Number_of_Tasks") tempCell.Value = DateSerial(Year(tempCell.value), Month(tempCell.value) + 1, Day(tempCell.value)) Next tempCell