在数字在一个单元格和date中添加一个数字在另一个 – VBA中

我在列B中有一个date,列C中有一个数字(天数),并且希望将列c中的值添加到列B中的date。

| A | B | C | -------------------------------- Name 01/01/2016 5 Name2 09/01/2016 10 Name3 04/02/2016 3 

在这种情况下,第一行将成为06/01/2016,第二行将成为19/01/2016,第三行将成为07/02/2016。

然后我想检查添加是否小于TODAY,如果添加等于或大于TODAY,则突出显示单元格红色。

这是我的代码到目前为止。

 Private Sub Workbook_Open() Dim myDate As Date For Each cell In Range("B2", Range("B2").End(xlDown)) myDate = DateAdd("d", ) 'stuck here If myDate >= Date cell.Interior.ColorIndex = 3 cell.Font.ColorIndex = 2 cell.Font.Bold = True End If Next End Sub 

对代码进行了更改。 尝试这个:

 Private Sub Workbook_Open() Dim myDate As Date For Each cell In Range("B2", Range("B2").End(xlDown)) myDate = DateAdd("d", CDbl(cell.Offset(0, 1).Value), DateValue(cell.Value)) If myDate >= Now() Then cell.Interior.ColorIndex = 3 cell.Font.ColorIndex = 2 cell.Font.Bold = True End If Next End Sub 

尝试这个,但我认为由Kilian Hertel给出的答案是这样做的首选方法。

由于每当你打开工作簿时运行macros可能会继续添加C列中的数字,所以它会继续增加,我不知道是否需要。

 Private Sub Workbook_Open() Dim wk As Worksheet Set wk = Sheet1 'Change it to the preferred sheet number (!Not the Sheet Name) Dim FRow As Long FRow = wk.Range("B" & wk.Rows.Count).End(xlUp).Row 'Finding Last Row For Each cell In wk.Range("B2" & ":B" & FRow) 'Loop from B2 to B & Frow cell.Value2 = cell.Value2 + wk.Range("C" & cell.Row) 'Add the Date with the number in the corresponding row of `C` Column If cell.Value2 >= Date Then 'Check if the date in column B is greater than or equal to Today's Date 'If yes the do this cell.Interior.ColorIndex = 3 cell.Font.ColorIndex = 2 cell.Font.Bold = True Else: End If Next cell End Sub 

你不应该用Excel正常公式和条件格式来做到这一点吗?

我不会为此使用VBA。

如果您以标准格式正确格式化date,则会显示一个数字。 只需在ColumnD中计算DateCellNumber(Column B + ColumnC),然后我认为可以使用TODAY()公式进行条件格式化。

好吧?

另一种实现方式如下

 Private Sub Workbook_Open() Dim i As Long Dim myDate As Date lastrow = Range("A" & Rows.Count).End(xlUp).Row For i = 1 To lastrow Range("B" & i).Value = DateAdd("d", Range("B" & i).Value, CDate(Range("D" & i).Value)) If Range("B" & i).Value >= Now() Then Range("B" & i).Interior.ColorIndex = 3 Range("B" & i).Font.ColorIndex = 2 Range("B" & i).Font.Bold = True End If Next i End Sub