VBA中的工作日功能

时间:2017-02-05 12:23:05

标签: excel vba excel-vba

我尝试使用工作日功能在VBA中完成以下任务:

我想做的是:

  1. 我在col K中有日期,此代码应仅在工作日日期运行 而不是周末约会。

  2. 我需要添加其他文本以及"已移至SA(兼容性 减少)",让我们说"移动到SA(失败)" 。因此,如果col P具有"移动到SA(兼容性减少)"或者"移动到SA(失败)"着色应该发生。

  3. 此代码只能在工作表"延迟"

  4. 中运行

    我有以下代码,但它会抛出错误消息:

    wrong number of arguments or invalid property assignment
    

    我的代码:

    Sub Weekday()
    
    Dim r, LastRow, RemainingDay As Double
    
     LastRow = Range("M:O").Cells(Rows.count, "A").End(xlUp).Row
    
     Application.ScreenUpdating = False
    
         For r = 2 To LastRow
           RemainingDay = 0
    
            If Weekday(Range("K" & r).Value, vbMonday) = 2 Then
    
                  Select Case True
                         Case InStr(Range("P" & r).Text, "Moved to SA (Compatibility Reduction)") > 0, _
                        InStr(Range("P" & r).Text, "Moved to SA (Failure)") > 0
    
                     If Range("M" & r) - RemainingDay >= 1 Then
                         Range("M" & r).Cells.Font.ColorIndex = 3
                     Else
                          Range("M" & r).Cells.Font.ColorIndex = 0
                       End If
    
                End Select
             End If
        End If
    Next r
    
    End Sub
    

1 个答案:

答案 0 :(得分:1)

这是您为所要求的内容重构的子代码

我还将其以前的名称更改为WeekdayCheck() s而不是隐藏 VBA WeekDay()功能

Sub WeekdayCheck()
    Dim r As Long, LastRow As Long
    Dim RemainingDay As Double '<--| you seem no to use it! if so get rid of it

    With Worksheets("Latency") '<--| reference worksheet "Latency"
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).row '<--| get row index of its column A last not empty cell
        Application.ScreenUpdating = False
        For r = 2 To LastRow
            RemainingDay = 0 '<--| you seem no to use it! if so get rid of it

            If Weekday(.Range("K" & r).Value, vbSaturday) > 2 Then '<--| having 'Weekday()' function starting from "Saturday", it'll return numbers from 3 to 7 for not weekend weekdays
                Select Case True
                    Case InStr(.Range("P" & r).Text, "Moved to SA (Compatibility Reduction)") > 0, _
                         InStr(.Range("P" & r).Text, "Moved to SA (Failure)") > 0
                        If .Range("M" & r) - RemainingDay >= 1 Then
                            .Range("M" & r).Cells.Font.ColorIndex = 3
                        Else
                            .Range("M" & r).Cells.Font.ColorIndex = 0
                        End If
                End Select
            End If
        Next r
    End With
End Sub