如果下一列中有空白单元格,则串联两个单元格

时间:2018-10-16 13:53:25

标签: excel vba

我有一个简单的电子表格,有3万行。

在B列下,我有一个空白单元格,这将指示A列下的地址超过两行,我想将这两个单元格连接成一个单元格。

Sub Merge()

Dim LR As Integer
Dim icell As Range
Dim strMerge As String
Dim MyCell As Range

'Add new Sheet and rename it
Worksheets.Add After:=Worksheets("Austin Grids")
ActiveSheet.Name = "Austin Grids1"

'Copy sheets contents from original to the new sheet
Sheets("Austin Grids").Cells.Copy Destination:=Sheets("Austin Grids1").Range("A1")

'Find last row of current sheet
LR = Worksheets("Austin Grids1").Cells(Rows.Count, 1).End(xlUp).Row

Set MyCell = Sheets("Austin Grids1").Range("A:A")

'Move rows of where column is null
For Each icell In Range("B:B")
    If icell.Value = "" Then
        icell.Select
        icell.Offset(0, -1).Select
        strMerge = MyCell.Value
    End If
Next icell

End Sub

截屏:

2 个答案:

答案 0 :(得分:0)

您不需要使用VBA,因此,如果可以的话,我将提供公式解决方案。

H2中,粘贴此公式并根据需要向下拖动:

=IF(B1="",A1&" "&A2,"")

注意:您可能只需要A1&A2,我不知道A列中的这些名称中是否实际上有前导空格,或者是格式化的格式

然后,在I2中将其粘贴并向右拖动:

=IF($H2<>"",B2,"")

enter image description here

答案 1 :(得分:0)

这是您可以用于VBA的循环。它将从结尾开始,逐行向上移动,直到到达第2行。

Dim totalRows As Long, i As Long

totalRows = Range("A1").End(xlDown).Row

With Sheets("Austin Grids1")
For i = totalRows To 2 Step -1
    If .Cells(i, 2) = "" Then
        .Cells(i + 1, 1).Value = .Cells(i, 1).Value & .Cells(i + 1, 1).Value
        .Cells(i, 1).EntireRow.Delete
    End If
Next i
End With