如何使用 Excel VBA 在 table 中水平复制公式?

How to copy a formula horizontally within a table using Excel VBA?

所以我有这样的数据

前两个 table 正在对第三个 table 的某些数据进行平均。

我正在尝试编写一个宏来为每个 table 添加一个额外的列,并同时复制上一列中的公式。添加一个新列进行得很好,但是复制给我带来了问题。

这是我目前拥有的:

 Sub What()

Dim m As Integer
Dim n As Integer
Dim TableName As String
Dim i As Integer
Dim x As Integer
Dim LastRow As Integer

For i = 1 to 12
TableName = "Table" & i

    With ActiveSheet.ListObjects(TableName)

        .ListColumns.Add

    n = .ListColumns.Count
    m = n - 1

             'this is filling in the first row, with the column number (needed for formulas in the real data)
        .DataBodyRange(1, n).Value = n
        .DataBodyRange(1, n).NumberFormat = "General"

    LastRow = .ListRows.Count

             'this is where I'm trying to copy the formula over to the right
        For x = 2 To LastRow
            .DataBodyRange(x, n) = .DataBodyRange(x, m).Formula
        Next x

    End With

  Next i 

End Sub

这个问题是它直接复制了公式,所以我的 Table A1 的新列 F 仍然是 Table A3 的列 E 的值的平均值。

在我现在的代码之前,我试过自动填充(像这样:

Range("K4").Select
        Selection.AutoFill Destination:=Range("K4:L4"), Type:=xlFillDefault

)

但我不需要它来引用范围,我需要它来引用 table 单元格,la ActiveSheet.ListObjects("Table1").DataBodyRange(3, 2)。天真地我试图把它分到目的地

ActiveSheet.ListObjects("Table1").ListColumns.Add
        ActiveSheet.ListObjects("Table1").DataBodyRange(1, 2).Select
        Selection.AutoFill Destination:=ActiveSheet.ListObjects("Table1").DataBodyRange(1, 3), Type:=xlFillDefault

并被告知

Run-time error '1004': AutoFill method of Range class failed

我搜索过的所有资源都是指在一列中填写公式,但由于我的数据方向,我需要它水平复制,而不是垂直复制,但我还没有找到任何相关信息。有人可以帮我解决这个问题吗?

非常感谢~

  • Destination 应该包括 起点cell/range 和目的地cell/range。
  • AutoFill也可以一次性完成,而不是当前循环从第2行到最后一行。
  • 无需使用SelectSelection

然后像这样的东西演示了这个概念 - 根据需要修改:

Option Explicit

Sub AutoFillRight()
    Dim myTbl As ListObject: Set myTbl = Sheet1.ListObjects("Table1")
    Dim sourceRng As Range, destRng As Range
    Dim lastRow As Long, lastCol As Long

    With myTbl
        .ListColumns.Add

        lastRow = .ListRows.Count
        lastCol = .ListColumns.Count

        If lastRow > 1 Then
            Set sourceRng = Range(.DataBodyRange(2, lastCol - 1), .DataBodyRange(lastRow, lastCol - 1))
            Set destRng = Range(.DataBodyRange(2, lastCol - 1), .DataBodyRange(lastRow, lastCol))

            sourceRng.AutoFill Destination:=destRng, Type:=xlFillDefault
        End If
    End With
End Sub