如何获得excel VBA中天数的差异?

我目前正在使用Excel VBA开发一个图书馆系统项目,而且我需要一个模块来检查过期的书籍,以及计算过期书籍用户的罚款。

这是我有的代码,显然不工作。

Dim fine, count, count2 As Integer Dim currentdate, borroweddate, difference As String 'this is the amount of fine imposed per day (50 cents) fine = 1 / 2 'gets number of borrowing records count = Sheets("borrowing records").Range("K1").Value 'count2 is just a counter for the cells count2 = 2 'gets the current date currentdate = Now() While (count2 < count + 2) If (Sheets("borrowing records").Cells(count2, 8).Value = "ON LOAN") Then difference = currentdate - Sheets("borrowing records").Cells(count2, 4).Value If (difference > 20) Then 'prints the overdue record Sheets("display").Cells(count2, 1).Value = Sheets("borrowing records").Cells(count2, 1).Value Sheets("display").Cells(count2, 2).Value = Sheets("borrowing records").Cells(count2, 2).Value Sheets("display").Cells(count2, 3).Value = Sheets("borrowing records").Cells(count2, 3).Value Sheets("display").Cells(count2, 4).Value = Sheets("borrowing records").Cells(count2, 4).Value Sheets("display").Cells(count2, 5).Value = difference * fine End If Else count2 = count2 + 1 End If Wend Sheets("display").Select 

当我试着运行一个类似的代码来testing差异的价值时,我得到了很长的小数的随机数字。 我不知道为什么。 我得到的结果甚至没有接近实际的天差。 例如,如果我testing3月20日到3月1日之间的天数差异,我会得到类似于4.35648920486E32E的东西,是的,结果中有一个字母“E”。

我最初的意图是让代码在工作表中查找(“借用logging”),这是程序存储借用logging的地方。

该程序将比较该书的借阅date和当前date,以查看20天的限制是否到期。

如果是这样,它将通过date差额乘以每日罚款(在这种情况下是50美分)来计算罚款。 然后程序应该在另一个工作表(“显示”)上打印过期的logging以及罚款。

我知道这个程序是行不通的,可能是因为date的格式或类似的东西。 但是,我不知道如何解决这个问题。

我的项目在星期一到期,我只希望有人读这篇文章能帮助我。 谢谢!

由于我们的评论链太多, 我想我会开始一个新的答案:

对于你的date差异使用DateDiff函数是这样的:

 difference = DateDiff("d", currentdate, Sheets("borrowing records").Cells(count2, 4).Value, vbMonday) 

其中"d"表示不同的天数,而vbMonday告诉系统我们的星期从星期一开始(默认是星期天,我认为 – 现在怀疑与您有关,但请记住将来使用)

这会给你一个简单的天数答案,这就是你以后的。 乘以你的浮动罚款价值,我认为这是你目前的问题需要解决的一切。 不需要通过date格式,因为结果将只是一个正常的数字。

 Dim fine, count, count2 As Integer Dim currentdate, borroweddate, difference As String 'this is the amount of fine imposed per day (50 cents) fine = 1 / 2 ' integers don't do floating point! 

你看过fine的价值吗? 我想你可能会发现你欠你的逾期借款人;-)

这里发生了什么?

 difference = currentdate - Sheets("borrowing records").Cells(count2, 4).Value 

尝试添加一行,看看你是否得到你所期望的答案,像

 difference = currentdate - Sheets("borrowing records").Cells(count2, 4).Value Debug.Print currentdate, Sheets("borrowing records").Cells(count2, 4).Value, difference