簡體   English   中英

Excel VBA:將數據添加到上次使用的行之后的單元格

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

在此處輸入圖片說明 圖片顯示了我的代碼會發生什么。

我有一個用戶表單,並將用戶表單的標簽添加到所選工作表中。 這就是我嘗試過的。 現在的問題是為什么為什么一個單元格與其他單元格不在同一行?

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。但是一旦您將值設置為“ No. ” 在下一次您執行該代碼( 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM