首页 > 解决方案 > VBA 自动填充 - 单元格引用变量

问题描述

我正在尝试将 A 列中的最后一个单元格自动填充到 B 列中的最后一个单元格。

但是,每列中的最后一个单元格是可变的。

以下是我当前的代码:

Sub Import()

'Select first empty cell in column B
    Sheets("Sheet1").Select
    Range("B1").End(xlDown).Offset(1, 0).Select

'Paste  Data
    ActiveSheet.Paste
    
'Allocate source_file to pasted data
    Range("A1").End(xlDown).Offset(1, 0).Select
    Application.CutCopyMode = False
    ActiveCell.FormulaR1C1 = "TEMP"

End Sub

我在 A 列中找到了第一个空单元格并输入了“TEMP”。我现在想将其填充到 B 列的最后一行。

任何帮助,将不胜感激。

谢谢

标签: excelvbavariablesrangeautofill

解决方案


这应该这样做:

    Dim lastrowa As Long
    Dim lastrowb As Long
    
    With Sheet2
        lastrowa = .Cells(.Rows.Count, 1).End(xlUp).Row
        lastrowb = .Cells(.Rows.Count, 2).End(xlUp).Row
        
        .Cells(lastrowa + 1, 1).Value = "TEMP"
        .Cells(lastrowa + 1, 1).AutoFill .Range(.Cells(lastrowa + 1, 1), .Cells(lastrowb, 1))
    End With

推荐阅读