簡體   English   中英

Excel VBA - 將非空白單元格與下面的空白單元格合並

[英]Excel VBA - merging non-blank cells with blank cells below

我有一個具有以下布局的工作表:

Column title
Data1
              <- bank cell 1
              <- bank cell 2   
Data2
Data3
Data4
              <- bank cell 3
              <- bank cell 4
              <- bank cell 5
Data5

我想要做的是將空白單元格與上面的“數據”合並。

例如, blank cell 1blank cell 2應與單元格 Data1 合並, blank cell 3blank cell 4blank cell 5應與單元格 Data4 合並。

最終產品應具有以下布局:

Column title
Data1
              <- part of Data1, result of a merge
              <- part of Data1, result of a merge   
Data2
Data3
Data4
              <- part of Data4, result of another merge
              <- part of Data4, result of another merge
              <- part of Data4, result of another merge
Data5

我試圖通過計算數據單元格數量的偏移量來探測合並應該從哪里開始,然后在條件ActiveCell.Value <> ""變為假的地方激活單元格。 但我意識到我不知道如何更改活動單元格的位置,並且如果我繼續使用偏移量,當我嘗試進行第二次合並時它將不起作用,因為偏移量是單個選擇。

Cell("C3").Activate      'C3 is the Column title
Dim offset As Variant

While True:
    offset = 0
    While (ActiveCell.Value <> ""):    'I am trying to skip over the cells with contents
    offset = offset + 1
    Wend
    ' Here, ActiveCell.offset(offset - 1, 0) should give me the Data cell that I should merge with the blank cells below (to be calculated with a second loop), but I'm not sure how to make that cell the active cell.
Wend

如果有更好的方法來解決這個問題,請告訴我。

將找到的任何空白單元格與其上方的單元格合並。

    Dim i As Long
    Dim lr As Long
    Dim lastdata As Long
    
    With Sheets("Sheet1")'Change to your sheet name
        lr = .Cells(.Rows.Count, 1).End(xlUp).Row
        For i = 2 To lr 
            If .Cells(i, 1).Value = "" Then
                .Range(.Cells(i, 1).Offset(-1), .Cells(i, 1)).Merge
            End If
        Next i
    End With

暫無
暫無

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

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