繁体   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