简体   繁体   English

Excel VBA:将数据添加到上次使用的行之后的单元格

[英]Excel VBA: Add data to cell after last used row

在此处输入图片说明 The pic shows what happens with my code. 图片显示了我的代码会发生什么。

I have a user form and I add the labels of the user form into the selected worksheet. 我有一个用户表单,并将用户表单的标签添加到所选工作表中。 And this is what I tried. 这就是我尝试过的。 Now the problem is why is it that there is one cell not on the same row as the others? 现在的问题是为什么为什么一个单元格与其他单元格不在同一行?

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

The problem is that the first time you do .Cells(.Rows.Count, 1).End(xlUp).Row there will not be anything yet in A2, so lastRow will be 1. But once you put the value "No." 问题在于,第一次执行.Cells(.Rows.Count, 1).End(xlUp).Row A2中还没有任何内容,因此lastRow将为1。但是一旦您将值设置为“ No. ” in that cell the next time you execute that code (with i being 2), A2 will be filled, so now .Cells(.Rows.Count, 1).End(xlUp).Row will return 2, giving you the effect you get: all other values end up one row lower. 在下一次您执行该代码( i为2)时,将在该单元格中填充A2,因此现在.Cells(.Rows.Count, 1).End(xlUp).Row将返回2,为您带来效果得到:所有其他值最终降低一排。

There are several way to solve this, but here is one way. 有几种方法可以解决此问题,但这是一种方法。 Add + IIf(i = 1, 1, 0) the assignment of lastRow : 添加+ 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM