【问题标题】:Networkdays Function for range of cells in VBAVBA中单元格范围的Networkdays函数
【发布时间】:2017-08-25 21:08:35
【问题描述】:

我正在构建一个宏,它将 AO 列中的日期(日期格式 dd/mm/yyyy hh:mm)与 AL 列中的日期(日期格式 dd/mm/yyyy hh:mm)进行比较,它将打印他们在工作日与列 AS 的差异(只是天数,而不是分钟等)我已经搜索并发现 NETWORKDAYS 是 excel 中的一个函数,但我不知道如何在 VBA 中实现它的范围.到目前为止,我的代码与我在网上找到的代码非常相似,但它是针对特定日期的,而不是针对某个范围的。有任何想法吗?非常感谢!

到目前为止我所拥有的是这个,但它说有一个与 d1=cell.Offset 一致的错误...我现在不知道为什么!

Dim d1 As Range, d2 As Range, wf As WorksheetFunction
'Dim N As Long
Set wf = Application.WorksheetFunction
For Each cell In Range(Range("AT2"), Range("AT2").End(xlDown))
Set d1 = cell.Offset(0, -4)
Set d2 = cell.Offset(0, -7)
cell.Value = wf.NetworkDays(d1.Value2, d2.Value2)
Next cell

【问题讨论】:

  • 不是每个单元格都被视为一个循环吗?
  • 抱歉没有看到编辑。
  • 你需要Set范围:Set d1 = cell.Offset(0, -4)
  • 现在它说问题出在 cell.Value = wf.NetworkDays(d1, d2)
  • 你遇到了什么错误?

标签: vba excel date


【解决方案1】:

我建议采用“混合”方法,因为无论如何您都将使用工作表函数:让 VBA 填充函数,用值替换输出:

    Sub WorkDaysDiff()
    ' w-b 2017-08-26

    Dim rng As Range, lastrow As Long

    ' assuming columns A, B hold dates, results into column C
    lastrow = ActiveSheet.Range("A1").End(xlDown).Row
    With ActiveSheet
        Set rng = .Range(.Range("C1"), .Range("C" & lastrow))
    End With

    With rng
        ' write formula into worksheet cells for whole range at once
        ' and replace it with their value after recalculation
        .FormulaR1C1 = "=NETWORKDAYS(RC[-1],RC[-2])"
        .Copy
        .PasteSpecial xlPasteValues
        Application.CutCopyMode = False
    End With
End Sub

这样,您可以避免循环,如果范围足够大,可能会节省时间。

【讨论】:

    【解决方案2】:

    您不需要 VBA。它也可能是一个 VBA 函数,我不确定。

    【讨论】:

    • 我知道如何在 excel 中手动完成,但它是宏的一部分,所以它必须在 vba 中!
    【解决方案3】:

    试试这个

        Dim d1 As Date, d2 As Date
    
        For Each Cell In Range(Range("AT2"), Range("AT2").End(xlDown))
            d1 = Cell.Offset(0, -4)
            d2 = Cell.Offset(0, -7)
            Cell.Value = Application.WorksheetFunction.NetworkDays(d1, d2)
        Next Cell
    

    【讨论】:

    • 它说第 d1 行的类型不匹配 = Cell.Offset(0, -4)
    • 这意味着您的数据不是日期类型,而可能是字符串。所以你不能对数据进行日期操作。
    【解决方案4】:

    如果您想使用 AL 和 AO 列,并将结果放入 AS - 范围由 AT 中的内容确定 - 使用以下内容:

    Dim d1 As Range, d2 As Range, wf As WorksheetFunction
    'Dim N As Long
    Set wf = Application.WorksheetFunction
    For Each cell In Range(Range("AT2"), Range("AT2").End(xlDown))
    Set d1 = cell.Offset(0, -5)
    Set d2 = cell.Offset(0, -8)
    cell.Offset(0, -1).Value = wf.NetworkDays(d1.Value2, d2.Value2)
    Next cell
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多