我试图编写一个简单的跟踪程序,但不能教它正确地逐行填写报告。
这个想法是:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
'define last row in report
<proper code for it>
'fill in "last row +1" with tracking info
<proper code for it as well>
End Sub
所以我尝试了两种选择:
1)使用Cells()属性(而不是Offset
,行索引可能只有LastRow + 1
)
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
LastRow = ThisWorkbook.Sheets(1).Cells(ThisWorkbook.Sheets(1).Rows.Count, 1).End(xlUp).Row
ThisWorkbook.Sheets(1).Cells(LastRow, 1).Offset(1, 0).Value = 1
End Sub
它会导致多行填充所需的值。奇怪的是,在工作表中的每次更改后,它总是花费93行所选单元格(所以93 186 279 372 465 558)。
2)使用Range()属性:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
LastRow = ThisWorkbook.Sheets(1).Cells(ThisWorkbook.Sheets(1).Rows.Count, 1).End(xlUp).Row
ThisWorkbook.Sheets(1).Range("A1").Offset(LastRow, 1).Value = 1
End Sub
然后它正确填充所需的单元格,但随后不断导致
运行时错误&#39; -2147417848(80010108):对象的方法范围 _worksheet失败
在三次之一中,它也会导致Excel崩溃。
答案 0 :(得分:1)
您的代码会触发SheetChange事件,因为代码会写入工作表,因此代码会创建一个重复循环。尝试关闭事件然后重新开启。
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Application.EnableEvents = False
LastRow = ThisWorkbook.Sheets(1).Cells(ThisWorkbook.Sheets(1).Rows.Count, 1).End(xlUp).Row
ThisWorkbook.Sheets(1).Cells(LastRow, 1).Offset(1, 0).Value = 1
Application.EnableEvents = True
End Sub
答案 1 :(得分:0)
您可能正在重新触发事件。之前禁用事件:
ThisWorkbook.Sheets(1).Cells(LastRow, 1).Offset(1, 0).Value = 1
然后重新启用它们。