Dynamic Autofill Destination

本秂侑毒 提交于 2021-02-04 19:22:05

问题


Need some help with this code:

Dim numRows As Long

numRows = Cells(Rows.Count, "A").End(xlUp).Row

Selection.AutoFill Destination:=Range(Cells(1, 12), Cells(numRows, 12)), Type:=xlFillDefault

The macro is supposed to fill column L with a formula. It works with files with multiple rows but ends with:

Autofill method of Range class failed.

For files with only one row.


回答1:


Tips:

  1. Avoid the use of Selection. In your code, the selection may not be the "selection" you think it is ;) You may want to see How to avoid using Select in Excel VBA

  2. Your objects are not fully qualified. You may want to see THIS

  3. You can use .Formula to enter the values in the entire range in one go.

Is this what you are trying (Untested)?

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long

    Set ws = Sheet1 '<~~ Change as applicable

    With ws
        '~~> Get the last row
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        .Range("L1:L" & lRow).Formula = .Range("L1").Formula
    End With
End Sub



回答2:


Test if the row count is equal to or lower than zero with an if statement:

Dim numRows As Long

With Sheets("Yoursheetname")

    numRows = .Cells(.Rows.Count, "A").End(xlUp).Row

    If Not numRows <= 1 Then .Cells(1, 12).AutoFill Destination:=.Range(.Cells(1, 12), .Cells(numRows, 12)), Type:=xlFillDefault

End With

As per my comment, you could also use On Error Resume Next:

Dim numRows As Long

numRows = Cells(Rows.Count, "A").End(xlUp).Row

On Error Resume Next 'turn of error handling for the next statement

Selection.AutoFill Destination:=Range(Cells(1, 12), Cells(numRows, 12)), Type:=xlFillDefault

On Error GoTo 0 'turn error handling back on

Edit: as per @Peh's comment, the first one is preferred, as turning off error handling (even for one statement) might become problematic if you code has (or develops) any other issues.




回答3:


Alternatively:

Sub Test()

Dim lr As Long

With Sheet1
    lr = .Cells(.Rows.Count, 1).End(xlUp).Row
    If lr > 1 Then .Range("L1:L" & lr).FillDown
End With

End Sub


来源:https://stackoverflow.com/questions/59945293/dynamic-autofill-destination

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!