简体   繁体   English

Excel VBA - 将非空白单元格与下面的空白单元格合并

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

I have a worksheet with the following layout:我有一个具有以下布局的工作表:

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

What I want to do is to merge the blank cells along with the "data" right above.我想要做的是将空白单元格与上面的“数据”合并。

For example, blank cell 1 and blank cell 2 should be merged with cell Data1, and blank cell 3 , blank cell 4 , and blank cell 5 should be merged with cell Data4.例如, blank cell 1blank cell 2应与单元格 Data1 合并, blank cell 3blank cell 4blank cell 5应与单元格 Data4 合并。

The ending product should have the following layout:最终产品应具有以下布局:

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

I tried to probe where the merging should start by calculating an offset of the number of Data cells, then activate the cell right where the condition ActiveCell.Value <> "" becomes false.我试图通过计算数据单元格数量的偏移量来探测合并应该从哪里开始,然后在条件ActiveCell.Value <> ""变为假的地方激活单元格。 But I realized that I don't know how to change the location of the active cell, and if I keep using offsets, it would not work when I try to do a second merge, as the offset is a single selection.但我意识到我不知道如何更改活动单元格的位置,并且如果我继续使用偏移量,当我尝试进行第二次合并时它将不起作用,因为偏移量是单个选择。

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

If there are better ways to do this problem, please let me know.如果有更好的方法来解决这个问题,请告诉我。

Merge any blank cell found with the cell above it.将找到的任何空白单元格与其上方的单元格合并。

    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