从日期格式中减去整数 VBA

subtracting integer from a date format VBA

下面是我开发的代码。 objective 是从数据中减去“1”或“2”,分别取决于是星期六还是星期日。第 3 列包含短日期格式的日期,第 5 列包含相同的日期但已转换为 "dddd" 格式。

错误发生在第

行的for循环中
if cells(i,5).Value = "Sat" Then

这里有趣的是,代码运行时没有 "error",它只是跳过了那一行的 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() 方法 return 是一个表示一周中某一天的整数,基于您提供的开始日期。 Weekday(.Value, vbSaturday) 会在周六 return 1,周日会 2。结合立即数 If IIf() 我们可以检查值 returned 是否小于 3(例如 1 或 2),如果是,则从 C

列中的日期中减去该值

column 5 contains the same dates but converted to "dddd" format

"dddd" 公开了 "Saturday" 而不是 "Sat" 公开了 "ddd".

仍然尝试将 Cells(i,5).Value 更改为 Cells(i,5).Text:

If Cells(i,5).Text = "Sat" Then ....

If Cells(i,5).Text = "Saturday" Then ....