VBA对于每个单元格

时间:2018-01-31 20:44:58

标签: vba excel-vba excel

我有一个包含A到H列数据的工作表。列A和B中的某些单元格没有值或为空,但是在该行中有其他列的值是C到H.现在我有这个代码来做这个。循环遍历B中的每个空单元格并输入值。这是我的代码将填充到B中的最后一个非空单元格但是我收到错误。

Sub filldownemptyAB()     
 Dim cel As Range, rng As Long
rng = Cells(Rows.Count, 1).End(xlUp).row

For Each cel In rng.Cells
 With ActiveCell
 .Offset(, 0).Formula = "=year(today())"
.Offset(, -1).Value = "Actual"
End With
Next cel
  End Sub

错误在此行

 For each cel in rng

2 个答案:

答案 0 :(得分:4)

我相信你正在寻找这个:

(我编辑了几次以简化操作并扫描列B而不是列A

Sub FillDownEmptyAB()
Dim c, lr
lr = ActiveSheet.UsedRange.Rows.CountLarge
For Each c In Range("B1:B" & lr)
    If c.Value = "" Then
        c.Offset(,-1).Value = "Actual"
        c.Formula = "=YEAR(TODAY())"
    End If
Next c
End Sub

输入:

Input

输出:

Output

答案 1 :(得分:2)

Long不是Ranges的集合。

我认为你正在尝试做这样的事情:

Sub filldownemptyAB()     
  Dim cel As Range
  Dim lastRow As Long
  lastRow = Cells(Rows.Count, 1).End(xlUp).row

  Dim rng as Range
  Set rng = Range("B" & lastRow)

  For Each cel In rng
    With cel
      .Offset(, 0).Formula = "=year(today())"
      .Offset(, -1).Value = "Actual"
    End With
  Next cel
End Sub

但这很难说。