Excel VBA:将数据添加到最后使用的行之后的单元格
图片显示了我的代码发生了什么。
我有一个用户表单,并将用户表单的标签添加到选定的工作表中。 这就是我的尝试。 现在的问题是,为什么有一个单元格与其他单元格不在同一行?
Dim c As Control For Each c In Me.Controls If TypeName(c) = "Label" Then With ActiveSheet i = i + 1 Dim lastRow As Long lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1 If c <> "Chapter" Then .Range(Cells(1, 1), Cells(1, i)).Name = "Chapter1" .Range("Chapter1").Merge .Range("Chapter1").Value = "Chapter 1" .Range("Chapter1").HorizontalAlignment = xlCenter .Cells(lastRow, i).Value = c.Caption End If End With End If Next
问题是,你第一次做.Cells(.Rows.Count, 1).End(xlUp).Row
在A2中没有任何东西,所以lastRow
将是1.但是一旦你把值“ “ 在这个单元格中,下一次执行代码( i
是2),A2将被填充,所以现在.Cells(.Rows.Count, 1).End(xlUp).Row
将返回2,给你效果得到:所有其他值最终降低一行。
有几种方法可以解决这个问题,但这里是一个方法。 添加+ IIf(i = 1, 1, 0)
lastRow
+ IIf(i = 1, 1, 0)
lastRow
的赋值:
lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row + IIf(i = 1, 1, 0)