【问题标题】:Looking for a way to Autofill Using a Variable Range寻找一种使用可变范围自动填充的方法
【发布时间】:2021-04-12 08:37:00
【问题描述】:

我正在寻找一种方法,使用一个可变范围将我的公式自动填充到数据集中的最后一行(可变)。我在底部突出显示了我的问题。

这是我现在拥有的代码:

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

【问题讨论】:

标签: excel vba autofill


【解决方案1】:

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

【讨论】:

  • 工作完美。我让自己变得比需要的更难:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-04
  • 2016-09-19
  • 2023-02-02
  • 2011-10-05
  • 1970-01-01
相关资源
最近更新 更多