如何创建一个宏,将在一个单元格中添加一天并同时在另一个单元格中减去一天?这是我到目前为止所拥有的。
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
我知道您已经接受了答案,但我想提供这种方法,它比遍历所有这些单元格更快、更有效。
如果您的日期在 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
抵消救援!
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