问题
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:
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 VBAYour objects are not fully qualified. You may want to see THIS
You can use
.Formulato 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