如何debugging我简单的Excel VBAmacros?

我只是试图检查当前date在列A中的最新date单元格。 如果差异是30天,我写一个新的行。

当我执行时,它说我不能在工作表上调用CheckAttendance(“发生”)。 但为什么?

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 

编辑:这可能有多个问题。 我固定了很多东西,但后来被卡住了。

看来你想参数化你的CheckAttendance程序,以便可以在不同的工作表上调用它。 要做到这一点,使它成为一个工作表作为参数的子。 此外

  • 在代码中限定您的单元格和范围
  • 调暗您的variables并使用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