Excel VBA 上下自动填充
Excel VBA autofill across and down
好的...我正在努力解决可能很简单的问题...我在单元格 B2 中有一个公式,我想填充到最后一个包含数据或格式的单元格(与按 CTRL+ 时相同END) 或者换句话说 "the bottom right corner" 我的数据。我该怎么做呢? "A"列和“1”行中有数据...所以需要填充到包含数据的最后一行和最后一列...
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
lastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
Range("B2").AutoFill Destination:=Range(Range("B2"), Cells(2, lastCol)), Type:=xlFillDefault
Range("B2:B" & lastCol).AutoFill Destination:=Range("B2"), Cells(lastRow, lastCol)), Type:=xlFillDefault
以下代码可帮助您确定和参考您的 "box range." 该代码做出了 3 个假设,如果不正确,您可能需要修改这些假设:
1) 你方框范围的"top left corner"是B2
2) Col B 中的值跨越范围的底部。如果您希望 Col B 中有空白,请将其更改为不同的列。
3) 第 2 行中的值跨越您使用的列的末尾。如果您希望第 2 行中有空白,请将其更改为不同的行。
Sub RangeBox()
Dim WS As Worksheet
Set WS = ThisWorkbook.Sheets(1)
Dim LRow As Long
Dim LCol As Long
LRow = WS.Range("B" & WS.Rows.Count).End(xlUp).Row
LCol = WS.Cells(2, Columns.Count).End(xlToLeft).Column
MsgBox "Last Row: " & LRow & vbNewLine & "Last Column: " & LCol
'How to refer to the box range starting from A1
Dim Start As Range
Set Start = WS.Range("B2")
WS.Range(Start, WS.Cells(LRow, LCol)).Select
End Sub
要用公式填充此范围:
WS.Range(Start, WS.Cells(LRow, LCol)).Formula = "=Sum(1,2)"
在引号内,像在 excel 中一样输入公式,并在需要时使用锁定引用 ($)。上面的示例将用值 3 填充您的范围。
好的...我正在努力解决可能很简单的问题...我在单元格 B2 中有一个公式,我想填充到最后一个包含数据或格式的单元格(与按 CTRL+ 时相同END) 或者换句话说 "the bottom right corner" 我的数据。我该怎么做呢? "A"列和“1”行中有数据...所以需要填充到包含数据的最后一行和最后一列...
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
lastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
Range("B2").AutoFill Destination:=Range(Range("B2"), Cells(2, lastCol)), Type:=xlFillDefault
Range("B2:B" & lastCol).AutoFill Destination:=Range("B2"), Cells(lastRow, lastCol)), Type:=xlFillDefault
以下代码可帮助您确定和参考您的 "box range." 该代码做出了 3 个假设,如果不正确,您可能需要修改这些假设:
1) 你方框范围的"top left corner"是B2
2) Col B 中的值跨越范围的底部。如果您希望 Col B 中有空白,请将其更改为不同的列。
3) 第 2 行中的值跨越您使用的列的末尾。如果您希望第 2 行中有空白,请将其更改为不同的行。
Sub RangeBox()
Dim WS As Worksheet
Set WS = ThisWorkbook.Sheets(1)
Dim LRow As Long
Dim LCol As Long
LRow = WS.Range("B" & WS.Rows.Count).End(xlUp).Row
LCol = WS.Cells(2, Columns.Count).End(xlToLeft).Column
MsgBox "Last Row: " & LRow & vbNewLine & "Last Column: " & LCol
'How to refer to the box range starting from A1
Dim Start As Range
Set Start = WS.Range("B2")
WS.Range(Start, WS.Cells(LRow, LCol)).Select
End Sub
要用公式填充此范围:
WS.Range(Start, WS.Cells(LRow, LCol)).Formula = "=Sum(1,2)"
在引号内,像在 excel 中一样输入公式,并在需要时使用锁定引用 ($)。上面的示例将用值 3 填充您的范围。