[英]How do I mark cells in my sheet for a macro to take values from? (Excel VBA)
I am trying to build a macro which should insert specified no.我正在尝试构建一个应该插入指定编号的宏。 of rows below specified row number.低于指定行号的行数。 Here's what I've tried so far:这是我到目前为止所尝试的:
Sub Macro2()
Dim iRow As Long
Dim iCount As Long
Dim i, j As Long
Dim length As Long
arrVal = Array(2, 3, 4) 'no. of rows to add
arrTar = Array(18, 19, 20) 'target row numbers to respectively add the no. rows specified above
length = 3 'length of above array
For j = 1 To length
iCount = arrVal(j)
iRow = arrTar(j)
For i = 1 To iCount
Rows(iRow).EntireRow.Insert
Next i
Next j
End Sub
The above code is inserting all the rows it's supposed to add (2+3+4=9) directly below first row no.上面的代码将所有应该添加的行 (2+3+4=9) 直接插入到第一行的下方。 (18). (18)。 What is wrong with my code?我的代码有什么问题? Again, all I want to do is add specified no.同样,我要做的就是添加指定的编号。 of rows below specified row no.指定行号以下的行数。 (as per arrays in my code, 2 rows below 18th row, 3 below 19th, etc.) (根据我的代码中的 arrays,第 18 行以下 2 行,第 19 行以下 3 行等)
I have just started with loops, so I am pretty confused on what to do here.我刚刚开始使用循环,所以我很困惑在这里做什么。
Please, test the next adapted code:请测试下一个改编的代码:
Sub InsertRows_Arrays()
Dim sh As Worksheet, iRow As Long, iCount As Long
Dim arrVal, arrTar, i As Long, j As Long, length As Long
Set sh = ActiveSheet
arrVal = Array(2, 3, 4) 'no. of rows to add
arrTar = Array(18, 19, 20) 'target row numbers to respectively add the no. rows specified above
length = UBound(arrVal) 'length of above array, in fact is 2. A 1D array is zero based
For j = LBound(arrVal) To length
iCount = arrVal(UBound(arrVal) - j): iRow = arrTar(UBound(arrTar) - j)
For i = 1 To iCount
sh.rows(iRow + 1).EntireRow.Insert xlUp
Next i
Next j
End Sub
1D arrays are 0 based, except the case when you have on top of the module Option Base 1
. 1D arrays 基于 0,除非您在模块Option Base 1
之上。 I used Ubound
to make it working for both cases.我使用Ubound
使它适用于这两种情况。
What was row 20 before the first insert becomes 22 after first insertions and 27 after the next three.第一次插入之前的第 20 行在第一次插入之后变为 22,在接下来的三个之后变为 27。 That's why the above code starts insertions from the last array element and of course, uses the correspondent number of rows from the other array...这就是为什么上面的代码从最后一个数组元素开始插入,当然,使用来自另一个数组的相应行数......
Please, test it and send some feedback.请测试它并发送一些反馈。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.