我有这样的数据:
前两个表格是从第三个表格中计算出来的。
我想编写一个宏,为每个表格添加一列,并同时复制上一列的公式。添加新列很容易,但复制公式却让我遇到了问题。
以下是我目前的代码:
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
这样做的问题在于它直接复制了公式,因此我的新表A1的列F仍然是将表A3的列E的值进行平均。
在我现在拥有的代码之前,我尝试了自动填充(就像这样:
Range("K4").Select
Selection.AutoFill Destination:=Range("K4:L4"), Type:=xlFillDefault
但我不需要它引用一个范围,我需要它引用一个表格单元格,就像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
并被告知
运行时错误 '1004': Range类的AutoFill方法失败
我搜索到的所有资源都是关于在列中填充公式,但由于我的数据方向,我需要将其水平而不是垂直复制,并且我没有找到任何相关内容。能否有人帮助我解决这个问题?
非常感谢~
AutoFill
中,Destination
不应该包括起始单元格和目标单元格两者吗? - BigBenRange
调用中,例如Range(.DataBodyRange(1, 2), .DataBodyRange(1, 3))
,可以使代码正常运行。您应该能够一次性获取ListColumn
的整个Range
(不包括第一个单元格),并向右自动填充,而无需循环遍历行。 - BigBenWith ActiveSheet.ListObjects("Table1") .ListColumns.Add .ListRows(2).Range.Select Selection.AutoFill Destination:=Range(.DataBodyRange(1, 2), .DataBodyRange(1, 3)), Type:=xlFillDefault End With
也出现了相同的错误。你能否分享一下你成功的代码?编辑 我也尝试过.ListColumns.Add .DataBodyRange(1, 2).Select Selection.AutoFill Destination:=Range(.DataBodyRange(1, 2), .DataBodyRange(1, 3)), Type:=xlFillDefault
,但不起作用。 - Sylphie