我的自动填充功能有问题。我想用宏来填充日期,直到B中没有任何内容为止。问题是那里有一些空白。我可以更改代码,使其填充到 B 中的最后一行吗?我用下面的代码尝试了它。然而,它不起作用。
Sub fill()
Sheets("Table1").Select
Columns("C:C").Select
Selection.Insert Shift:=xlToRight
Range("C2").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]="""",R[-1]C,RC[-1])"
ActiveCell.Select
Dim last As Long
Range("C2").Select
Range(Selection, Selection.End(xlToRight)).AutoFill Destination:=Range("C2:C" & last)
Selection.End(xlDown).Select
Selection.ClearContents
ActiveCell.Offset(-1, 0).Range("A1").Select
Range(Selection, Selection.End(xlUp)).Select
Selection.Copy
Range("B2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Columns("C:C").Select
Application.CutCopyMode = False
Selection.Delete Shift:=xlToLeft
Range("A1").Select
End Sub
最佳答案
您不需要这么漫长的过程。只需几行即可完成。例如
rng.SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=R[-1]C"
这是一个例子。假设您的范围是从 C2
开始,如下所示。
试试这个代码
Option Explicit
Sub Sample()
Dim ws As Worksheet
Set ws = Sheets("Table")
Dim lRow As Long
With ws
lRow = .Range("C" & .Rows.Count).End(xlUp).Row
Dim rng As Range
Set rng = .Range("C3:C" & lRow)
Dim visibleCells As Range
On Error Resume Next
Set visibleCells = rng.SpecialCells(xlCellTypeBlanks)
On Error GoTo 0
If Not visibleCells Is Nothing Then
visibleCells.FormulaR1C1 = "=R[-1]C"
End If
End With
End Sub
实际行动
值得一提
- 还要避免使用
Select/Selection/Activecell
等。您可能需要阅读 How to avoid using Select in Excel VBA - 您不需要 VBA 来实现您想要的。只需点击几下即可实现相同的目的。
非 VBA 方法
- 选择您的范围。在本例中
C3:C13
- 按 CTRL + G 调出转到对话框
- 点击特殊按钮
- 选择空白单选按钮,然后单击确定。
- 在公式栏中输入
=C2
并按 CTRL + ENTER 键即可完成
实际行动
关于excel - 如何使单元格范围在 VBA 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62797020/