【问题标题】:Excel VBA - merging non-blank cells with blank cells belowExcel VBA - 将非空白单元格与下面的空白单元格合并
【发布时间】:2022-01-26 14:02:33
【问题描述】:

我有一个布局如下的工作表:

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 &lt;&gt; "" 变为假的地方激活单元格。但我意识到我不知道如何更改活动单元格的位置,如果我继续使用偏移量,当我尝试进行第二次合并时它将不起作用,因为偏移量是一个单一的选择。

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

如果有更好的方法来解决这个问题,请告诉我。

【问题讨论】:

  • 目前还不清楚结果应该是什么样子(3-5 令人困惑)。为什么不将其布局添加到您的帖子中?
  • @VBasic2008 感谢您的反馈。我已经编辑了结果的布局。

标签: excel vba


【解决方案1】:

将找到的任何空白单元格与其上方的单元格合并。

    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

【讨论】:

  • 感谢您提供解决此问题的方法!