你好每个人都偷看,
我是VB的新手,我一直在尝试创建一些非常简单的网络代码。我正在努力计算两个带有日期值的单元格之间的周数。第一个单元格位于固定位置,第二个单元格是该列使用范围内的最后一个单元格。
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
答案 0 :(得分:4)
我认为你的错误是由于这一行:
nwks = (Cells(3, 2) - LastCell.Value) / 7
LastCell是一个字符串,因此它不需要.Value
nwks = (Cells(3, 2) - LastCell) / 7
您可以在VBA中使用DATEDIFF
功能。
DateDiff( interval, date1, date2, [firstdayofweek], [firstweekofyear] )
用法示例:
nwks = DateDiff("ww", Cells(3, 2).Value, LastCell.Value)
您可以查看DATEDIFF
HERE