【问题标题】:Autofill formulas with a dynamic range具有动态范围的自动填充公式
【发布时间】:2020-09-15 03:07:58
【问题描述】:

我在 G 列有我要分离的数据组合。 mid/find 的公式工作正常,但是当我尝试在底部添加我在网上找到的自动填充代码时,它会出错。

Range("H2").Select
ActiveCell.FormulaR1C1 = "=MID(RC[-1],FIND(""ASL"",RC[-1])+4,3)"

Range("I2").Select
ActiveCell.FormulaR1C1 = "=MID(RC[-2],FIND(""DEPT"",RC[-2])+5,2)"

Range("J2").Select
ActiveCell.FormulaR1C1 = "=MID(RC[-3],FIND(""ST"",RC[-3])+3,2)"

Range("K2").Select
ActiveCell.FormulaR1C1 = "=MID(RC[-4],FIND(""REIN"",RC[-4])+5,5)"

Range("H2:K2").Select
Selection.AutoFill Destination:=Range("H2:K" & Range("A" & Rows.Count).End(xlUp))

【问题讨论】:

    标签: excel vba excel-formula autofill


    【解决方案1】:

    您可以通过将公式放入数组并将每个公式写入列范围来将公式写入每一列。你不需要使用AutoFill。此代码会将公式插入到列 H - K 从第 2 行到 A 列的最后一行(值)。请根据需要更改工作表。代码中提供了注释。

    Sub InsertFormulasInColumnsWithArray()
    
    'Set your worksheet variable, change the worksheet as needed
    Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
    
    'Put all your formulas into an array. the `_` connects each section into one line of code, easier to read.
    
    Dim formulaArr As Variant: formulaArr = Array("=MID(RC[-1],FIND(""ASL"",RC[-1])+4,3)", _
    "=MID(RC[-2],FIND(""DEPT"",RC[-2])+5,2)", "=MID(RC[-4],FIND(""REIN"",RC[-4])+5,5)", _
    "=MID(RC[-4],FIND(""REIN"",RC[-4])+5,5)")
    
    
    x = 8 'assign the variable `x` to the first column `H = 8`
    
        With ws 'use the With statement to ensure you are adding the formulas to the correct worksheet
        
            For i = LBound(formulaArr) To UBound(formulaArr) 'loop through the 4 formulas in your array
            
                'Starting at `row 2`, `column 8` (x = 8)`,
                'resize the the range to the value of the last row in `Column A`
                'you subtract `-1` because you start the range on `Row 2`
                'Write the first formula to the range in `Column H`,
                'in the second loop you will write the second formula in Column I, etc.
    
                .Cells(2, x).Resize(.Cells(.Rows.Count, 1).End(xlUp).Row - 1).FormulaR1C1 = formulaArr(i)
                
                x = x + 1 'increase x by 1 to select the next column
                
            Next i 'Loop to the next formula in the array, until the last formula is done
        End With
    
    End Sub
    

    【讨论】:

    • 谢谢你这个工作,这肯定比我循环粘贴公式时快得多。但是,当我打开第二个文件并再次应用代码时,它似乎不起作用。如果我关闭宏并重新编写它,它会再次起作用。我需要重置一些东西吗?
    • 我将 Thisworkbook 更改为 ActiveWorkbook,它正在工作。
    • 很高兴我能帮上忙
    猜你喜欢
    • 1970-01-01
    • 2012-12-19
    • 2018-07-04
    • 1970-01-01
    • 2014-04-21
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多