Excel VBA自动填充横向和向下

时间:2018-05-23 19:41:50

标签: excel vba excel-vba fill autofill

好的......我正在努力做一些可能很简单的事情......我在单元格B2中有一个公式,我想填充包含数据或格式的最后一个单元格(与按CTRL + END时相同)或换句话说,我的数据的“右下角”。我该怎么做呢?列“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

1 个答案:

答案 0 :(得分:0)

以下代码可帮助您确定和引用您的"框范围。"该代码正在做出3个假设,如果不正确,您可能需要修改:

1)"左上角"你的盒子范围是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填充您的范围。