簡體   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