0

大家好,偷看,

我对 VB 非常陌生,我一直在使用一些网络代码来尝试创建一些非常简单的东西。我正在尝试让 excel 计算两个具有日期值的单元格之间的周数。第一个单元格位于固定位置,第二个单元格是该列使用范围内的最后一个单元格。

Last是我从网上摘下来的一个功能。我根本无法让它工作,任何帮助将不胜感激。

   Sub test_date_calc()



   Dim LastCell As String
   Dim nwks As Integer
   Dim rng As Range

   Set rng = Sheets("data13").UsedRange
   LastCell = Last(3, rng)
   nwks = (Cells(3, 2) - LastCell.Value) / 7
   If nwks > 13 Then

   MsgBox "greater"
   Else

   MsgBox "Less"

   End If
   End Sub

下面的Last功能,这可能会有所帮助

Function Last(choice As Long, rng As Range)
'Ron de Bruin, 5 May 2008
' 1 = last row
' 2 = last column
' 3 = last cell
    Dim lrw As Long
    Dim lcol As Long

    Select Case choice

    Case 1:
        On Error Resume Next
        Last = rng.Find(What:="*", _
                        After:=rng.Cells(1), _
                        Lookat:=xlPart, _
                        LookIn:=xlFormulas, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Row
        On Error GoTo 0

    Case 2:
        On Error Resume Next
        Last = rng.Find(What:="*", _
                        After:=rng.Cells(1), _
                        Lookat:=xlPart, _
                        LookIn:=xlFormulas, _
                        SearchOrder:=xlByColumns, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Column
        On Error GoTo 0

    Case 3:
        On Error Resume Next
        lrw = rng.Find(What:="*", _
                       After:=rng.Cells(1), _
                       Lookat:=xlPart, _
                       LookIn:=xlFormulas, _
                       SearchOrder:=xlByRows, _
                       SearchDirection:=xlPrevious, _
                       MatchCase:=False).Row
        On Error GoTo 0

        On Error Resume Next
        lcol = rng.Find(What:="*", _
                        After:=rng.Cells(1), _
                        Lookat:=xlPart, _
                        LookIn:=xlFormulas, _
                        SearchOrder:=xlByColumns, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Column
        On Error GoTo 0

        On Error Resume Next
        Last = rng.Parent.Cells(lrw, lcol).Address(False, False)
        If Err.Number > 0 Then
            Last = rng.Cells(1).Address(False, False)
            Err.Clear
        End If
        On Error GoTo 0

    End Select
End Function
4

1 回答 1

4

我认为你的错误是由于这一行:

 nwks = (Cells(3, 2) - LastCell.Value) / 7

LastCell 是一个字符串,所以它不需要.Value

 nwks = (Cells(3, 2) - LastCell) / 7

您可以DATEDIFF在 VBA 中使用该函数。

  DateDiff( interval, date1, date2, [firstdayofweek], [firstweekofyear] )

使用示例:

nwks = DateDiff("ww", Cells(3, 2).Value, LastCell.Value)

您可以在此处查看文档DATEDIFF

于 2013-11-01T13:53:06.310 回答