首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在excel VBA中获取天数的差值?

如何在excel VBA中获取天数的差值?
EN

Stack Overflow用户
提问于 2011-03-18 17:43:35
回答 2查看 2.9K关注 0票数 1

我目前正在做一个使用Excel VBA的图书馆系统项目,我需要一个模块来检查过期的书籍,以及计算对拥有过期书籍的用户施加的罚款。

这就是我拥有的代码,它显然不能工作。

代码语言:javascript
复制
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

当我尝试运行类似的代码来测试差值时,我得到的是带有很长小数的随机数。我也不知道原因。我得到的结果在几天内甚至没有接近实际的差值。例如,如果我测试3月20日和3月1日之间的天数差异,我将得到类似4.35648920486E32E的结果,是的,结果中曾经有一个字母"E“。

我的初衷是编写代码来搜索工作表(“借阅记录”),这是程序存储借阅书籍记录的地方。

该程序将比较这本书的借阅日期和当前日期,看看20天的限制是否到了。

如果是这样,它将通过将日期差值乘以每天的罚款金额(在本例中为50美分)来计算罚款。然后,程序应在另一个工作表(“显示”)中打印逾期记录以及罚款。

我知道这个程序不能工作,可能是因为日期的格式或类似的原因。然而,我不知道如何解决它。

我的项目周一到期,我只希望阅读这篇文章的人能帮助我完成它。谢谢!

EN

回答 2

Stack Overflow用户

发布于 2011-03-18 18:45:28

因为我们有太多的评论链了。我想我会开始一个新的回答:

对于日期差异,使用DateDiff函数,如下所示:

代码语言:javascript
复制
difference = DateDiff("d", currentdate, Sheets("borrowing records").Cells(count2, 4).Value, vbMonday)

其中"d"表示的差异是以天数提供的,vbMonday告诉系统我们的一周从周一开始(默认是周日,我想-现在可能与您相关,但请记住,以备将来使用)

这将给你一个简单的天数答案,这就是你想要的。将它乘以你的浮点型精细值,我认为这就是你当前所需要解决的问题。不需要经过日期格式化,因为结果将只是一个正常的数字。

票数 3
EN

Stack Overflow用户

发布于 2011-03-18 17:57:23

代码语言:javascript
复制
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的价值吗?我认为您可能会发现您向逾期借款人收取的费用过低;-)

这是怎么回事?

代码语言:javascript
复制
difference = currentdate - Sheets("borrowing records").Cells(count2, 4).Value

尝试添加一行,看看是否得到了预期的结果,如下所示

代码语言:javascript
复制
difference = currentdate - Sheets("borrowing records").Cells(count2, 4).Value
Debug.Print currentdate, Sheets("borrowing records").Cells(count2, 4).Value, difference
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5350237

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档