如何创建一个在一个单元格中添加一天并同时在另一个单元格中减去一天的宏?这是我到目前为止所拥有的。
Sub ChangeDates()
Dim cell As Range
For Each cell In Range("B:B")
cell.Value = cell.Value + 1
Next cell
For Each cell In Range("C:C")
cell.Value = cell.Value - 1
End Sub
答案 0 :(得分:3)
我知道你已经接受了答案,但我想提供这种方法,它比循环遍历所有这些单元更快更有效。
如果您的日期位于A列,则B列将保留date +1
,C列将保留date -1
Option Explicit
Sub ChangeDates()
Dim myRange As range
Dim mySheet As Worksheet
Set mySheet = Sheets("Sheet7") 'change to your sheet
With mySheet
Set myRange = .range("A1:A" & .range("A" & .Rows.Count).End(xlUp).Row)
myRange.Offset(, 1).FormulaR1C1 = "=RC[-1]+1"
myRange.Offset(, 2).FormulaR1C1 = "=RC[-2]-1"
End With
End Sub
答案 1 :(得分:0)
抵消救援!!
Sub ChangeDates()
Dim cell As Range
For Each cell In Range("B:B")
cell.Value = cell.Value + 1
cell.offset(0,1).value = cell.offset(0,1).value - 1
Next cell
End Sub
你可以考虑的另一件事是要么看看usedrange不必迭代所有的B列,要么进行检查以确保单元格不是空白...只是更快,更好的编码并阻止你细胞最初空白的坏值......
Sub ChangeDates()
Dim cell As Range
For Each cell In Intersect(Range("B:B"), ActiveSheet.UsedRange)
cell.Value = cell.Value + 1
cell.Offset(0, 1).Value = cell.Offset(0, 1).Value - 1
Next cell
End Sub