下面是我开发的代码。目标是从数据中减去“1”或“2”,具体取决于分别是星期六还是星期日。第 3 列包含短日期格式的日期,第 5 列包含相同的日期但转换为“dddd”格式。
错误发生在该行的 for 循环中
if cells(i,5).Value = "Sat" Then
这里有趣的是,代码运行时没有出现“错误”,它只是跳过了该行的 if 语句。
Sub DataChange()
Dim i
Dim n
n = Cells(Rows.Count, 3).End(xlUp).Row
For i = 4 to n
If Cells(i,5).Value = "Sat" Then
Cells(i,3).Value = Cells(i,3).Value - 1
End If
If Cells(i,5).Value = "Sun" Then
Cells(i,3).Value = Cells(i,3).Value - 2
End If
Next i
End Sub
最佳答案
只需将其全部替换为:
For i = 1 To Cells(Rows.Count, 3).End(xlUp).Row
With Cells(i, 3)
.Value = .Value - IIf(Weekday(.Value, vbSaturday) < 3, Weekday(.Value, vbSaturday), 0)
End With
Next
Weekday()
方法根据您提供的开始日期返回一个表示一周中某一天的整数。 Weekday(.Value, vbSaturday)
将返回 1
星期六,和 2
星期天。结合立即 If IIf()
我们可以检查返回的值是否小于 3(例如 1 或 2),如果是,则从 C 列中的日期中减去该值
关于excel - 从日期格式 VBA 中减去整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35289945/