簡體   English   中英

Excel將行復制到空白單元格

[英]Excel copy rows down to blank cells

我正在嘗試將包含數據(在單元格A,B,C,D中)的行向下復制到同一單元格(在不同行中)(如果單元格為空)。 因此,如果前面的單元為空,則基本上將數據復制到上面的單元中。 我的代碼如下:

Sub PadOut()
With Range("A2:D300") ' change this
  On Error Resume Next
  Set aRange = .SpecialCells(xlCellTypeBlanks)  'check for blank cells
  On Error Goto 0
  If Not aRange Is Nothing Then   
     aRange.FormulaR1C1 = "=R[-1]C"   
     .Value = .Value   
  End If
End With
End Sub

目前,我已將其設置在一個設定的范圍內。但是如何設置以便可以擴大范圍(如果我不知道總行數)

這是您要達到的目標嗎? 您可以根據需要更改開始行和列的編號。 endCol變量定義了要掃描的最后一個endRow循環在定義的列范圍內找到了最后使用的行。

Sub PadOut()

    Application.ScreenUpdating = False

    Dim startRow As Long
    startRow = 2
    Dim startCol As Long
    startCol = 1
    Dim endCol As Long
    endCol = 3

    With ActiveSheet

        Dim row As Long
        Dim col As Long
        Dim endRow As Long

        Dim bottomRow As Long
        bottomRow = ActiveSheet.Rows.Count
        Dim colEndRow As Long
        endRow = 0
        For col = startCol To endCol
            If (Cells(bottomRow, col).End(xlUp).row > endRow) Then
                endRow = Cells(bottomRow, col).End(xlUp).row
            End If
        Next col

        For col = startCol To endCol
            For row = startRow + 1 To endRow
                If .Cells(row, col).value = "" Then
                    .Cells(row, col).value = .Cells(row - 1, col).value
                End If
            Next row
        Next col

    End With

    Application.ScreenUpdating = True

End Sub
Sub PadOut()
lastRow = ActiveSheet.UsedRange.Rows.Count
if cells(lastRow, 1) = "" and cells(lastRow, 2) = "" and cells(lastRow, 3) = "" and cells(lastRow, 4) = "" then
  lastRow = WorksheetFunction.Max(cells(lastRow, 1).end(xlup).row, cells(lastRow, 2).end(xlup).row, cells(lastRow, 3).end(xlUp).row, cells(lastRow, 4).end(xlup).row)
end if

With Range("A2:D" & lastRow)
  On Error Resume Next
  Set aRange = .SpecialCells(xlCellTypeBlanks)  'check for blank cells
  On Error Goto 0
  If Not aRange Is Nothing Then   
     aRange.FormulaR1C1 = "=R[-1]C"   
     .Value = .Value   
  End If
End With
End Sub

您可以使用以下命令獲取總行數:

numberRows = ActiveSheet.UsedRange.Rows.Count

然后,您可以相應地設置范圍。

您實際上不需要VBA即可完成此任務。 可以使用選擇頁面和數組填充來完成。

為此,請執行以下操作: 突出顯示范圍 ,從第一行和包含要填充的空白數據的單元格開始。 接下來, 按CTRL + G ,這將顯示“轉到”窗口, 按特殊...。 選擇“空白”選項,然后按OK。 這將選擇您范圍內的所有BLANK單元。 然后,無需單擊(否則您將更改選擇),鍵入: = {按向上箭頭},然后按CTRL + ENTER

您的數據之前 // 您的數據之后

在此處輸入圖片說明 在此處輸入圖片說明

暫無
暫無

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

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