VBA宏中具有IF Else的工作日功能

时间:2019-01-24 19:32:16

标签: excel vba

我试图编写宏来复制以下Excel公式。

= if($L2>(workday($I2,7)),">T+7",if($L2>(workday($I2,2)),">T+2","SPOT"))

其中L2表示DD / MM / YYYY格式的一些较早的日期,而I是当前日期。 请提出建议。

数据看起来像这样 The data look like this

1 个答案:

答案 0 :(得分:0)

此代码首先在“ I”列中找到最后使用的行。
然后,它遍历所有行并填充一个数组,该数组最后分配给结果列:

Private Sub WorkDayDifferenceSub()
    Dim ws As Worksheet
    Dim r As Long
    Dim lastRow As Long
    Dim myResults() As String

    Set ws = ActiveWorkbook.Worksheets("YourWorksheetnameHere")

    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

    ReDim myResults(2 To lastRow, 1 To 1)

    For r = 2 To lastRow
        If ws.Cells(r, 12) > WorksheetFunction.WorkDay(ws.Cells(r, 9), 7) Then
            myResults(r, 1) = ">T+7"
        Else
            If ws.Cells(r, 12) > WorksheetFunction.WorkDay(ws.Cells(r, 9), 2) Then
                myResults(r, 1) = ">T+2"
            Else
                myResults(r, 1) = "SPOT"
            End If
        End If
    Next r

    ws.Range("AG2:AG" & lastRow).Value = myResults

    Set ws = Nothing
End Sub