gpt4 book ai didi

excel - 寻找一种使用可变范围自动填充的方法

转载 作者:行者123 更新时间:2023-12-04 08:18:29 27 4
gpt4 key购买 nike

我正在寻找一种方法来使用也是可变的范围将我的公式自动填充到数据集中的最后一行(可变)。我在底部突出显示了我的问题。
这是我现在拥有的代码:

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

关于excel - 寻找一种使用可变范围自动填充的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65598473/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com