我正试图跟踪我们财务模型的变化。目的是找出谁在背解。
我写的代码执行,直到我从一个工作表切换到另一个特定的工作表。
Sub tracker()
Dim Cell As Range
For Each Cell In Sheets("Input check IC").Range("AI2:AI128")
If Cell.Value <> 0 Then
With Sheets("Copy IC")
Sheets("Change tracker").Range("C10000").End(xlUp).Offset(1, 0).Resize(, 33).Value = .Range(.Cells(Cell.Row, "A"), .Cells(Cell.Row, "AG")).Value
End With
End If
Next
For Each Cell In Sheets("Input check IC").Range("AI2:AI128")
If Cell.Value <> 0 Then
With Sheets("Live IC")
Sheets("Change tracker").Range("C10000").End(xlUp).Offset(1, 0).Resize(, 33).Value = .Range(.Cells(Cell.Row, "A"), .Cells(Cell.Row, "AG")).Value
End With
End If
Next
'Live IC
Sheets("Live IC").Range("B2:AG128").Copy
Sheets("Copy IC").Range("B2").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
End Sub
我有一个重复的代码"RC"式中:IC =投资案例;RC =参考情况。RC在一个单独的模块中从跟踪器2调用。
当我转到工作簿中的任何工作表时,代码执行完美,除了RC(来自IC)/IC(来自RC)。我可能会添加当工作表停用时调用的代码。当我连续停用/激活IC/RC时,我觉得代码陷入了循环。
直到出现以下错误
运行时错误'-2147417848(80010108)':方法'Insert'对象'Range'失败'
复制范围
- 假设工作簿中的所有工作表都包含此代码。 请注意,数组将更有效地处理这个问题。把它当作范围的教训。
- 不是测试。
Option Explicit
Sub tracker()
Dim wb As Workbook: Set wb = ThisWorkbook
Dim cws As Worksheet: Set cws = wb.Worksheets("Input check IC")
Dim dst As Worksheet: Set dst = wb.Worksheets("Change tracker")
Dim sws As Variant: ReDim sws(1 To 2)
Set sws(1) = wb.Worksheets("Copy IC")
Set sws(2) = wb.Worksheets("Live IC")
Dim crg As Range: Set crg = cws.Range("AI2:AI128")
Dim drg As Range
Set drg = dst.Cells(dst.Rows.Count, "C").End(xlUp) _
.Resize(, 33).Offset(1, 0)
Dim srg As Range
Dim n As Long
Dim i As Long
For n = 1 To 2
Set srg = sws(n).Range("A2").Resize(crg.Rows.Count, 33)
For i = 1 To crg.Cells.Count
If crg.Cells(i).Value <> 0 Then
drg.Value = srg.Rows(i).Value
Set drg = drg.Offset(1)
End If
Next i
Next n
'Live IC
sws(1).Range("B2:AG128").Value = sws(2).Range("B2:AG128").Value
End Sub