繁体   English   中英

如何在工作表中标记单元格以供宏从中获取值? (Excel VBA)

[英]How do I mark cells in my sheet for a macro to take values from? (Excel VBA)

我正在尝试构建一个应该插入指定编号的宏。 低于指定行号的行数。 这是我到目前为止所尝试的:

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

上面的代码将所有应该添加的行 (2+3+4=9) 直接插入到第一行的下方。 (18)。 我的代码有什么问题? 同样,我要做的就是添加指定的编号。 指定行号以下的行数。 (根据我的代码中的 arrays,第 18 行以下 2 行,第 19 行以下 3 行等)

我刚刚开始使用循环,所以我很困惑在这里做什么。

请测试下一个改编的代码:

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
  1. 1D arrays 基于 0,除非您在模块Option Base 1之上。 我使用Ubound使它适用于这两种情况。

  2. 第一次插入之前的第 20 行在第一次插入之后变为 22,在接下来的三个之后变为 27。 这就是为什么上面的代码从最后一个数组元素开始插入,当然,使用来自另一个数组的相应行数......

请测试它并发送一些反馈。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM