如何在一个单元格中获取由两个空格分隔的单元格范围

时间:2015-01-22 06:32:51

标签: excel vba excel-vba concatenation

我需要一个vba代码来将由两个空格分隔的单元格值范围连接到另一个单元格中 例如。

 
a1  a
a2  b
a3  c
a4 blank
a5 blank
a6 d
a7 e
a8 f

那么单元格B的值将是

b1  a,b,c
b2  d,e,f

此代码汇总单个范围和concat空间。我希望空格是一个分隔符,并在空格之后连接范围并循环它。

Sub demo()
    'i = 2
    'if cells(i,2).value
    Dim lastRow As Long
    lastRow = ActiveSheet.Range("a" & Rows.Count).End(xlUp).Row
    MsgBox (lastRow)
    For i = 2 To lastRow
        'Do Until Cells(i, 2).End(xlDown).Row = ""
        If Cells(i, 3).Value = "" Then
            Sheet2.Cells(i, 1).Value = Cells(i, 1) & " " & Cells(i, 2)
        Else
            Sheet2.Cells(i, 1).Value = Cells(i, 1) & " " & _
                Cells(i, 2) & "(" & Cells(i, 3) & ")"
        End If
        ' i = i + 1
    Next i
End Sub     

1 个答案:

答案 0 :(得分:0)

你可以试试这个。这解决了您的第一个问题。我不明白你是在第二部分提出另一个问题,还是试图解释第一部分。无论如何,sub将单个空白视为要处理的范围的一部分。图中的示例输出。

只需更改输入范围(下面的“A1:A30”)。它将结果放在与输入数据相邻的列中。

Public Sub spaced_out()

Dim rr, Ain As Range
Dim AB As Object

Dim rr_out_count As Integer

Set Ain = ActiveSheet.Range("A1:A30")
Set AB = CreateObject("scripting.dictionary")

For Each rr In Ain
    If (rr.Value <> "") Then
            AB.Add rr.Row(), rr.Value
    ElseIf (rr.Value = "" And rr.Offset(1, 0).Value = "") Then
            rr_out_count = rr_out_count + 1
            Ain.Offset(0, 1).Cells(rr_out_count, 1).Value = Join(AB.items(), ",")
            AB.RemoveAll
    End If
Next


End Sub

enter image description here