简体   繁体   中英

How to combine 2 cell value into one cell with VBA?

在此处输入图像描述

How to use VBA combine Col A and B together with ";",and remove Col A and B after combined,

在此处输入图像描述

Try below sub-

Sub MergeCells()
Dim rng As Range
Dim LastRow As Long

  LastRow = Cells(Rows.Count, "A").End(xlUp).Row
  
  For Each rng In Range("A2:A" & LastRow)
    rng = rng & ";" & rng.Offset(0, 1)
    rng.Offset(0, 1).Clear
  Next

End Sub

Concatenate Columns

Option Explicit

Sub ConcatColumns()
    
    Const wsName As String = "Sheet1"
    Const Cols As String = "A:B"
    Const Col As String = "A"
    Const fRow As Long = 2
    Const Delimiter As String = ";"
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
    
    Dim lRow As Long: lRow = ws.Cells(ws.Rows.Count, Col).End(xlUp).Row
    If lRow < fRow Then Exit Sub ' no data
    Dim rCount As Long: rCount = lRow - fRow + 1
    Dim rg As Range: Set rg = ws.Rows(fRow).Columns(Cols).Resize(rCount)
        
    rg.Columns(1).Value = Evaluate(rg.Address(0, 0) & "&""" _
        & Delimiter & """&" & rg.Columns(2).Address(0, 0))
    
    rg.Columns(2).ClearContents
    
End Sub

Thanks all, very useful answer

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM