我无法弄清楚为什么会发生这种情况(它只是间歇性地发生,但总是具有相同的功能)......
我在用户碰巧的地方插入了一些复制的行,并检查它们之间是否需要分页。
我在崩溃一次后设法恢复了Excel,并发现它在一条带有ActiveCell引用的行上停顿。我撇开了这条线,代码继续成功地逐行进入下一个ActiveCell参考。
我重新打开了包含代码的模板文件,它运行得很好。
我知道使用ActiveCell是不好的做法,但在这种情况下我不知道如何绕过它 - 我需要在用户所在的位置添加行。
我应该这样做吗?
Dim R As Range
Set R = ActiveCell.Address
是否会保留原始的ActiveCell地址,还是会在代码运行且ActiveCell发生变化时动态更新?
非常感谢您的帮助!
[编辑]:代码(请原谅它正在开发中):
Sub InsertArea()
'Dimension variables
Dim SR
Dim Rng2 As Range
Dim i, j, PB1 As Integer
Dim Crit() As String
Dim w As Worksheet
i = 2
j = 0
PB1 = 0
Set Rng = Nothing
'NEW PAGE
'Check for page height breach
'Assign PB1 to selection row
PB1 = Selection.Row
'Reset i to 1
i = 1
'Loop how many extra blank rows you want below the bottom spec on a page
Do Until i = 17
'If there's a page break above row i
If Rows(PB1).Offset(i, 0).EntireRow.PageBreak <> xlPageBreakNone Then
'Copy blank row
Range("A1000:A1006").EntireRow.Copy
Selection.EntireRow.Insert Shift:=xlDown
'Insert page break just above the new area
Rows(PB1).Offset(4, 0).PageBreak = xlPageBreakManual
Selection.Offset(7, 0).Select
i = 17
Else
'Increment i to prevent infinite loop
i = i + 1
End If
Loop
'INSERT NEW AREA
'Copy blank new area
ActiveWorkbook.Names("Temp_NewArea").RefersToRange.EntireRow.Copy
'Paste (insert) that line by shifting cell up, so target cell remains in the new blank row
BUGS HERE
ActiveCell.EntireRow.Insert Shift:=xlUp
'ASSIGN NEW AREA WITH A NEW NAME
SR = ActiveWorkbook.Names("Spec1").RefersToRange.Address
'Amend selection to Quoted Specifications
ActiveCell.Offset(2, 7).Resize(4, 1).Select
'ADD THE NEW AREA TO SPECIFIED_RANGES
'Add that specified range to string SR, comma separated
SR = SR & ":" & Range("Quote_End").Offset(-3, 1).Address
'Create/Overwrite (by default) Specified_Areas range using string SR
ActiveWorkbook.Names.Add "Specified_Ranges", "=" & SR
ActiveCell.Offset(4, -7).Activate
Application.EnableEvents = True
Application.ScreenUpdating = True
Application.CutCopyMode = False
End Sub
答案 0 :(得分:1)
不要在整个代码中使用ActiveCell
,而应立即将其分配给变量并使用该变量。
Sub InsertArea()
'Dimension variables
Dim SR
Dim Rng2 As Range
Dim i, j, PB1 As Integer
Dim Crit() As String
Dim w As Worksheet
'Then declare your cell in question
Dim myCell As Range
Set myCell = ActiveCell
这可以防止代码运行时ActiveCell
无意中发生更改的情况。
此外,在您的声明中
Dim i, j, PB1 As Integer
我&amp; j被声明为类型Variant
,而PB1被声明为类型Integer
。虽然在一行上声明多个变量是完全可以接受的,但这些声明必须明确地完成,例如:
Dim i As Integer, j As Integer, PB1 As Integer
- 或 -
Dim i%, j%, PB1%
%
是Integer的VB符号,可用于声明变量。
根据OP请求发布为答案