在 VBA 中自动填充多列

问题描述 投票:0回答:1

我想使用 VBA 自动填充多个不相邻的列。我已经尝试了一些方法,目前正在尝试使用 for 循环来遍历每一列以连续自动填充每一列。我的 For 循环不起作用。

代码:

  Dim lRow As Long
    lRow = Cells(Rows.Count, "A").End(xlUp).Row
    
    
    Selection.Formula = "=IF(RC[2]<0,RC[1]*-1,RC[1])"
    
'    Selection.AutoFill Destination:=ActiveCell.Range("A1:A" & lRow)
    
    Dim cel As Range
    
    For Each cel In Selection.Cells
        Selection.AutoFill Destination:=cel.Range("A1:A" & lRow)
    Next cel

选择:enter image description here

我收到运行时错误“1004” Range 类的 AutoFill 方法失败

我的 for 循环有什么问题?或者,我还能怎样做?

我在评论行中留下了我的第一次失败的尝试

excel vba
1个回答
0
投票

此处无需自动填充 - 您可以直接分配公式。

试试这个:

Sub Tester()
    Dim lRow As Long, c As Range, sel As Range
    
    Set sel = Selection
    lRow = Cells(Rows.Count, "A").End(xlUp).Row
    
    For Each c In sel.Cells
        c.Resize(1 + (lRow - c.Row)).FormulaR1C1 = "=IF(RC[2]<0,RC[1]*-1,RC[1])"
    Next c
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.