作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用一些 VBA 代码来复制一系列单元格并将其值粘贴到下一个空行中 2111 次。
这成功粘贴到 754507 行,之后它崩溃了。
我可以在调试中看到它在第 1000 个循环处停止。
Option Explicit
Sub Paste_APIROWS()
Application.ScreenUpdating = False
Dim i As Long
Range("A2:H754").Copy
For i = 1 To 2111
Range("A2:H754" & i).PasteSpecial Paste:=xlPasteValues
Debug.Print i
Next i
Application.CutCopyMode = False
End Sub
The error message I get is "Run-time error '1004': Method 'Range' of object'_Global' failed"
最佳答案
在脑海中运行循环:
i = 1
,则范围为 "A2:H7541"
(行 2
到 7,541
)i = 2
,则范围为 "A2:H7542"
(行 2
到 7,542
)i = 9
,则范围为 "A2:H7549"
(行 2
到 7,549
)i = 10
,则范围为 "A2:H75410"
(行 2
到 75,410
)i = 99
,则范围为 "A2:H75499"
(行 2
到 75,499
)i = 100
,则范围为 "A2:H754100"
(行 2
到 754,100
)i = 900
,则范围为 "A2:H754900"
(行 2
到 754,900
)i = 999
,则范围为 "A2:H754999"
(行 2
到 754,999
)i = 1000
,则范围为 "A2:H7541000"
(行 2
到 7,541,000
)i
的每个值每经过 10 次方,行数就会增加一个数量级:
i = 9
至i = 10
你从行 7,549
至75,410
i = 99
至i = 100
你从行 75,499
至754,100
i = 999
至i = 1000
你从行 754,100
至7,541,000
2
- 所以在每次迭代中,你总是会覆盖自己。
1,048,576
行,因此崩溃。限制为
65,355
在 Excel 2007 之前或在现代版本的 Excel 中使用非 OOXML 电子表格时)。
I expect in the end to have about
1,589,583
rows but instead appear to be only getting about half of this.
1,589,583
无论如何行(如前所述,最大值为 1,048,576
)。 &
运算符)而不是数字加法。
A2:H754
范围内的单元格一些 2111 1930 次 - 这意味着你实际上想要这样做:
Const sourceRowLB = 2
Const sourceRowUB = 755 ' 755 not 754 because exclusive upper-bounds are easier to work with
Dim sourceRowCount = sourceRowUB - sourceRowLB
Dim lastCopyUB = 755
Dim sourceRangeExpr = GetRangeExpr( "A", sourceRowLB, "H", sourceRowUB ) ' Will be "A2:H754"
Range( sourceRangeExpr ).Copy
Const loopCount As Integer = 1389 ' This cannot be 2111 because ( 2111 * 754 ) exceeds the maximum row count
For i = 1 ToloopCount ' Loop 1389 times
' Recompute the destination range:
Dim destRowLB As Integer
destRowLB = lastCopyUB
Dim destRowUB As Integer
destRowUB = destRowLB + sourceRowCount
Dim rangeExpression As String
rangeExpression = GetRangeExpr( "A", destRowLB, "H" & destRowUB )
Range( rangeExpression ).PasteSpecial Paste:=xlPasteValues
lastCopyUB = destRowUB
Next i
Function GetRangeExpr(startCol As String, startRow As Integer, endCol As String, endRowExclUB As Integer) As String
GetRangeExpr = startCol & CStr( destRowLB ) & ":" & endCol & CStr( endRowExclUB - 1 ) ' We convert endRowExclUB to an inclusive upper-bound here
End Function
关于Excel VBA FOR LOOP 在第 1000 次崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55995145/
我是一名优秀的程序员,十分优秀!