如何调试我的简单Excel VBA宏?

时间:2017-06-07 21:25:08

标签: excel vba excel-vba

我只想尝试检查当前日期的A列中的最新日期单元格。如果差异是30天,我会写一个新行。

当我执行时,它表示我无法在工作表上调用CheckAttendance(" Occurences")。但为什么?

    Option Explicit

    Public LastCell As Long
    Public today As Date


    Function CheckAttendance()

        Dim DaysSinceOcc As Integer

        'returns last occupied row
        LastCell = Cells(Rows.Count, 1).End(xlUp).Row

        'gets current date
        today = Date

        'subtracts last cell in specified column from today's date.
        DaysSinceOcc = today - Cells(LastCell, 1).Value

        'writes what I want written in the cells I want it written in.        
        If DaysSinceOcc > 29 Then
            Cells(LastCell, 1).Offset(1, 1) = "winback"
            Cells(LastCell, 1).Offset(1, 2) = -0.5
            Cells(LastCell, 1).Offset(1, 4) = "Earned back 0.5 pts for 30 days perfect attendance (AutoGenerated)"
            Cells(LastCell, 1).Offset(1, 5) = "AUTO"
            Cells(LastCell, 1).Offset(1, 0) = today
        Else

        End If


    End Function

    Sub Attendance()

        Sheets("Occurences").CheckAttendance
        'yes Occurences is suppose to be spelled like that (don't ask)

    End Sub

编辑:这可能存在多个问题。我修了很多东西,但后来卡住了。

1 个答案:

答案 0 :(得分:2)

您似乎希望参数化CheckAttendance例程,以便可以在不同的工作表上调用它。为此,请将其设为Sub,将工作表作为参数。此外

  • 在代码
  • 中限定单元格和范围
  • 调暗变量并使用Option Explicit
Option Explicit

Sub CheckAttendance(ws As Worksheet)
    Dim DaysSinceOcc As Long, lastRow As Long, today As Long
    lastRow = ws.Cells(ws.Rows.count, 1).End(xlUp).row

    'gets current date
    today = Date

    'subtracts last cell in specified column from today's date.
    DaysSinceOcc = today - ws.Cells(lastRow, 1).Value2

    'writes what I want written in the cells I want it written in.
    If DaysSinceOcc > 29 Then
        ws.Cells(lastRow + 1, 1) = today
        ws.Cells(lastRow + 1, 2) = "winback"
        ws.Cells(lastRow + 1, 3) = -0.5
        ws.Cells(lastRow + 1, 5) = "Earned back 0.5 pts for 30 days perfect attendance (AutoGenerated)"
        ws.Cells(lastRow + 1, 6) = "AUTO"
    End If
End Sub

Sub Attendance()
    CheckAttendance Sheets("Occurences") ' <-- this is how you call it on any worksheet
End Sub