1

我目前正在使用 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

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

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

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

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

我知道该程序无法运行,可能是因为日期的格式或类似的东西。但是,我不知道如何解决它。

我的项目将于周一到期,我只是希望有人阅读此内容能帮助我完成它。谢谢!

4

2 回答 2

3

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

对于您的日期差异使用DateDiff功能,如下所示:

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

where"d"表示以天数提供的差异,并vbMonday告诉系统我们的一周从星期一开始(我认为它默认为星期日 - 现在怀疑与您相关,但请记住以备将来使用)

这将为您提供一个简单的天数答案,这就是您所追求的。将它与您的浮动罚款值相乘,我认为这就是您解决当前问题所需要的全部。无需进行日期格式化,因为结果只是一个普通数字。

于 2011-03-18T10:45:27.637 回答
0
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
于 2011-03-18T09:57:22.650 回答