excel - 从日期格式 VBA 中减去整数

标签 excel vba function date subtraction

下面是我开发的代码。目标是从数据中减去“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/

相关文章:

c# - 使用 EPPlus 在 GDI+ Drawings.AddPicture 中发生一般性错误

excel - 我想比较 Excel 中不同工作表中的两个列表以查找任何重复项

vba - Vlookup 返回空白而不是 0 或 #N/A

c - 如何通过特定参数过滤结构数组?

c++ - 错误 : Iso c++ forbids comparison between pointer and integer [c++]

javascript - 为什么 console.log 函数返回 undefined?

java - 使用 apache poi 3.7 多次写入 xlsx 文档时出现异常

excel - 在 excel 中从另一个插件启动一个插件

excel - 双击一个单元格以使用 VBA 显示来自 Excel 中链接的图片

vba - 如何使用 VBA 仅复制值