【问题标题】:Add one day to a date field in all cells in a row - VBA在一行中的所有单元格中的日期字段中添加一天 - VBA
【发布时间】:2017-11-02 04:29:42
【问题描述】:

我在 D1 单元格中有一个日期 (2/1/2018),现在我想使用 VBA 在从 D2 到 AH 的所有单元格中将日期增加一个

有什么建议吗?

谢谢 斯里

【问题讨论】:

    标签: vba excel date add


    【解决方案1】:

    请注意,如果变量数据类型设置为Date,则与 1 相加时会增加日期。

    VBA:

    Sub DateIncreaser
    
        Dim d as Date
        d = Selection.value 'Assign appropriated value to d variable.
        d = d + 1
        debug.print d 'This optional line shows the result in immediate window.
        Range("D2").Value = d
    
    End Sub
    

    更新1

    Sub DateIncreaser()
    
        Dim d As Date
        Dim i As Integer
        Dim InitialColumnIndex As Integer
        Dim FinalColumnIndex As Integer
        Dim RowsIndex As Long
    
        InitialColumnIndex = 1
        FinalColumnIndex = 34 'Representative AH Column
        RowsIndex = 2
        d = Selection.Value 'Source date value
    
        For i = InitialColumnIndex To FinalColumnIndex
            d = d + 1
            Cells(RowsIndex, i).Value = d
        Next i
    
    End Sub
    

    更新2

    Sub DateIncreaser()
    
        Dim d As Date
        Dim i, j As Integer
        Dim InitialColumnIndex As Integer
        Dim FinalColumnIndex As Integer
        Dim RowsIndex As Long
    
        InitialColumnIndex = 1
        FinalColumnIndex = 34 'Representative AH Column
        RowsIndex = 2
    
        For j = 1 To Sheets.Count
    
            d = Range("D1").Value 'Source date value
    
            For i = InitialColumnIndex To FinalColumnIndex
                d = d + 1
                Worksheets(j).Cells(RowsIndex, i).Value = d
            Next i
    
        Next j
    
    End Sub
    

    【讨论】:

    • 感谢您的回复。根据您的代码,它将仅在 D2 中增加值。我需要对从 D2 到 AH 的所有单元重复此操作。我使用了 Range("E1").Value = DateAdd("d", 1, CDate(Range("D1")))。但在这里它也只会将增加的值放入 E1 。我需要为所有单元格重复相同的代码行。有什么替代方案吗?
    • 更新已发送。
    • 非常感谢。有效。如果我想将日期放在所有工作表的单元格 D1 中(这里工作表名称是 Jan、Feb、Mar 等),我尝试了下面的代码。但它没有用。对于 j = 1 到 Sheets.Count Sheetname = Sheets(j).Name Worksheets("&Sheetname".Cells(RowsIndex, j).Value)=CDate(mm & "/01/" & Yr)。你能帮忙吗?(在这种情况下,mm 有 01,02,03 等对应于 jan,feb 等,Yr 将有 YYYY 年)
    • 请检查 update2。如果属实,请点击我答案左侧答案投票下的勾号,接受我的答案。
    • 感谢您告诉我。我是这个论坛的新手。我确实接受了您的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    相关资源
    最近更新 更多