我正在嘗試構建一個應插入指定編號的宏。低于指定行號的行數。這是我迄今為止嘗試過的:
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)。我的代碼有什么問題?同樣,我想要做的就是添加指定的編號。指定行號以下的行數 (根據我的代碼中的陣列,第 18 行以下 2 行,第 19 行以下 3 行,等等)
我剛剛開始使用回圈,所以我很困惑在這里做什么。
uj5u.com熱心網友回復:
請測驗下一個改編的代碼:
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
一維陣列是基于 0 的,除非您在模塊之上
Option Base 1。我曾經Ubound使它適用于這兩種情況。第一次插入之前的第 20 行在第一次插入之后變成了 22,在接下來的三個插入之后變成了 27。這就是為什么上面的代碼從最后一個陣列元素開始插入,當然,使用另一個陣列中對應的行數......
請測驗它并發送一些反饋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/367851.html
