遍历每个 table 行并插入不同的公式

Loop through every table row and insert different formula

我有一个带有预定义行和列的 table。我想遍历每一行并将不同的公式放入每个单元格。该单元格应显示来自不同工作表的数据。对每一列重复此步骤。

                                      Repeat:
+--------+--------+-----+---------+  1 || 2 ->
|Column 1|Column 2| ... | Column n|  |
+--------+--------+-----+---------+  |
|row 1   | row 1  | ... | row 1   |  |
+--------+--------+-----+---------+  v
|                ...              |
+--------+--------+-----+---------+
|row n   | row n  | ... | row n   |
+--------+--------+-----+---------+

我尝试使用 for 循环,它运行到最后一行并将带有 .FormulaLocal 方法的公式放入当前单元格。

For i = 1 To UBound(bmPos)
        curTable.DataBodyRange.Cells(i, curTable.ListColumns("Column1").Index).FormulaLocal = _
                "=Table1!" & wksBM.Cells(bmPos(i), rngDate.Column).Address
        [...]
        curTable.DataBodyRange.Cells(i, curTable.ListColumns("ColumnN").Index).FormulaLocal = _
                "=Table1!" & wksBM.Cells(bmPos(i), rngCustomer.Column).Address
Next i

预期的结果是每个单元格 i 包含如下公式: =Table1!$A$1 ... =Table1!$A$ i

当我使用调试器单步执行我的代码时,我看到的是,在第一次迭代中,所有 行获得相同的值。所以在最后一次迭代之后,所有行都包含公式 =Table1!$A$ i

事实上,当我用 i 替换整个公式时,我在单元格中得到了正确的迭代步骤。

Excel Table 正在使用您在任意行输入的最后一个公式自动填充整列。

为防止这种情况,请将 Application.AutoCorrect.AutoFillFormulasInLists = False 放在您的子文件的开头。