问题描述
我正在寻找一种方法,使用一个也是可变的范围将我的公式自动填充到数据集中的最后一行(这是可变的)。我在底部突出显示了我的问题。
这是我现在拥有的代码:
Sub MissingData()
Dim LastRow As Long
Dim LastCol As Long
Set ws = Worksheets("Insert Data")
With ws
Last Row = .Cells(.Rows.Count,1).End(xlUp).Row
Last Col = .Cells(1,.Columns.Count).End(xlToLeft).Column
'Inserting Column Header next to the last column in the data set in row 1"
.Cells(1,LastCol + 1).Value = "Header"
'Inserting Formula next ot the last column in the data set in row 2"
.Cells(2,LastCol + 1).Formula = "=iferror(AJ2,""YES"")"
End With
Dim FoundCell As Range
'Looking for the Last Row in the Dataset"
'Column A:A will always be populated with data and will be the driver
'for how many rows are in the data set"
LR = Worksheets("Insert Data").Range("A:A").End(xlDown).Row
With ws
'I set this and then called it using select because my range above
'and the location of this cell Could be variable"
Set FoundCell = .Cells(2,LastCol + 1)
FoundCell.Select
'Here lies my issue. Using this Syntax the formula is filled all the way
'to the last row available in Excel which is like 1 million something.
'I just need it filled to the last Now that i set above"
Selection.AutoFill Destination:=Range(ActiveCell,ActiveCell.End(xlDown))
End With
End Sub
解决方法
AutoFill
的更好替代方法是一次性输入整个范围内的公式。这是你正在尝试的吗?
Option Explicit
Sub MissingData()
Dim LastRow As Long
Dim LastCol As Long
Dim ws As Worksheet
Dim LastColName As String
Set ws = Worksheets("Insert Data")
With ws
'~~> Find last row
LastRow = .Cells(.Rows.Count,1).End(xlUp).Row
'~~> Find last column and add 1 to it
LastCol = .Cells(1,.Columns.Count).End(xlToLeft).Column + 1
'~~> Get Column name from column number
' https://stackoverflow.com/questions/10106465/excel-column-number-from-column-name
LastColName = Split(.Cells(,LastCol).Address,"$")(1)
'~~> Add header
.Range(LastColName & 1).Value = "Header"
'~~> Add the formula in the entire range in ONE GO
' Example: Range("D2:D" & LastRow).Formula = "=IFERROR(AJ2,""YES"")"
.Range(LastColName & 2 & ":" & LastColName & LastRow).Formula = "=IFERROR(AJ2,""YES"")"
End With
End Sub