如何使用VBA将3列合并到1个新列

时间:2016-09-07 14:59:48

标签: excel vba excel-vba

我正在尝试合并3列,它们都有文本(字符串)

我们可以说A列是这样的:

  1. 嗨,“你来自哪里?
  2. 嗨,“你来自哪里?
  3. 嗨,“你是来自?

    B栏:

  4. 彼得

  5. 妈妈
  6. C栏:

    1. DK
    2. JP
    3. GB
    4. 我希望我在D栏中输出:

      1. 嗨彼得“你来自DK?
      2. 嗨妈妈“你来自JP?
      3. 嗨爸爸“你们来自GB?
      4. 我自己的代码是:

        Sub MergeColumns()
        
            Dim LR As Long
            Dim cell As Range, RNG As Range
        
            LR = Range("A" & Rows.Count).End(xlUp).Row
            Set RNG = Range("A1:A" & LR)
        
            For Each cell In RNG
                   cell.Offset(0, 4) = Left(cell.Value, 2) & Range(B1:B) &   Mid(cell.Value, 4, 13) & Range(C1:C) & Right(cell.Value, 1)
            Next cell
        
            Range("C:C").Columns.AutoFit
        
        End Sub
        

        我认为这个bug在我的Range(B1:B)和Range(C1:C)中,但我不知道如何插入我尝试使用“Concatenate”的列,但这只是搞砸了。

2 个答案:

答案 0 :(得分:2)

我会在Replace functions上使用一对Range.Value2 property

Option Explicit

Sub wqwewuy()
    Dim rw As Long, lr As Long

    With ActiveSheet
        lr = .Cells(.Rows.Count, "A").End(xlUp).Row
        For rw = 1 To lr
            .Cells(rw, "D") = Replace(Replace(.Cells(rw, "A").Value2, _
                                        Chr(34), .Cells(rw, "B").Value2 & Chr(34)), _
                                        Chr(63), .Cells(rw, "C").Value2 & Chr(63))
        Next rw
    End With
End Sub

答案 1 :(得分:2)

之前的答案是一个很好的解决方案,您也可以这样做。

Sub MergeColumns()

    Dim LR As Long
    Dim cell As Range, RNG As Range

    LR = Range("A" & Rows.Count).End(xlUp).Row
    Set RNG = Range("A1:A" & LR)

    For Each cell In RNG
        cell.Offset(0, 3) = Left(cell.Value, 2) & " " _
                    & cell.Offset(0, 1) & " " _
                    & Mid(cell.Value, 4, 13) & " " _
                    & cell.Offset(0, 2) & Right(cell.Value, 1)
    Next cell

    Range("C:C").Columns.AutoFit

End Sub