![](/img/trans.png)
[英]How to loop over a multi-row/column range per column using Excel 2007 VBA?
[英]Excel VBA - Setting one-row worksheet range of formula to blank multi-row range, relative references skipping rows
Excel VBA - 將相對公式的單行工作表范圍設置為空白的多行范圍,相對引用跳過行
我正在嘗試為 Excel 工作簿模板的用戶創建一個宏,以便:
1) 在命名范圍內添加行,
2) 將此命名范圍中的最后一條記錄移動到此新行范圍中的頂行(以維護命名范圍的邊界並保留任何用戶輸入記錄的順序),以及
3)用來自主行的公式填充這些新行。
我卡住的地方是當主行公式設置為多個空白行的這個范圍時,相對引用(在第一行之后)跳過一行。 例如,如果此范圍內的第一行是第 16 行,則:
第 16 行有一個對 A16 的公式引用,
第 17 行將該引用設置為 A18,
第 18 行將該引用設置為 A20 等。
以下是用於執行此任務的子程序:
Option Explicit
Public Sub AddRows( _
ByRef rrngInputFields As Range, _
ByRef rrngMasterRow As Range, _
ByVal intRowsToAdd As Long)
'Add rows to worksheet
'rrngInputFields is the named range that defines user input fields
'rrngMasterRow is the row that contains template formula
'intRowsToAdd is the number of rows to add, determined by the user
Dim rngRefRow As Range
Dim rngLastRecordOldRow As Range
Dim intLastRecordNewNo As Integer
Dim rngNewRows As Range
Dim rngLastRecordNewRow As Range
Dim intCountCol As Integer
'Set the last user record in the user input range
'New rows will be added above this to preserve the range
Set rngRefRow _
= rrngInputFields.Cells(rrngInputFields.Rows.Count, 1).EntireRow
'Set the last user record to later be moved to the top of the added rows
'This will maintain the order the user input their data
Set rngLastRecordOldRow = rngRefRow
intLastRecordNewNo = rngRefRow.Row
'Add the new rows
rngRefRow.Resize(intRowsToAdd).Insert
intCountCol = rrngMasterRow.Columns.Count
'Set the range of new rows that will receive the template formula and formatting
Set rngNewRows _
= ActiveSheet.Range(Cells(intLastRecordNewNo + 1, 1), _
Cells(intLastRecordNewNo + intRowsToAdd, intCountCol))
'Set the row to move the last user input record
Set rngLastRecordNewRow = ActiveSheet.Rows(intLastRecordNewNo)
'Move the last user record to the bottom of the existing records
rngLastRecordNewRow.FormulaR1C1 = rngLastRecordOldRow.FormulaR1C1
'Copy the master row, including all formulas and formatting, to the added rows
rngNewRows.FormulaR1C1 = rrngMasterRow.FormulaR1C1
End Sub
最后一行是問題出現的地方。
什么會導致相對引用中的這種跳過?
這與此處備注中描述的 range.range 效果有關。 一個解決方案是使用range.copy方法這樣
'rngNewRows.FormulaR1C1 = rrngMasterRow.FormulaR1C1
rrngMasterRow.Copy rngNewRows
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.