excel - 添加一个数字到日期,其中数字在一个单元格中,日期在另一个单元格中 - VBA

标签 excel vba date

我在 B 列中有一个日期,在 C 列中有一个数字(天数)一直向下,我想将 c 列中的值添加到 B 列中的日期。

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

在这种情况下,第 1 行将变为 06/01/2016,第 2 行将变为 19/01/2016,而第 3 行将变为 07/02/2016。

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

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

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

最佳答案

试试这个,但我认为 Kilian Hertel 给出了答案是执行此操作的首选方法。

当您打开工作簿时运行宏可能会继续添加日期和 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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36788096/

相关文章:

php - 从当前日期减去月份返回意外结果

Excel 从两个表中查找最后一个匹配项

调用具有多个参数的 Sub 时 VBA 返回错误

Excel公式计算字符串右侧第一次出现的 '/'

excel - 如何遍历字母和数字序列 (I30112-J01111)

ms-access - VBA中的元组样式对象

java - 假期 - 有 java 实现吗?

excel - 宏仅复制可见单元格

vba - 在用户关闭 Excel 后,在 VBA - excel 中编写宏

angularjs - 使用 AngularJS 查找 2 个日期之间的差异