Merge the contents of 2 cells into another 3rd cell using VBA in Excel

后端 未结 4 1097
一整个雨季
一整个雨季 2021-01-20 01:18

I have two cells lets say: A1 and A2

The content of each one of them is a string:

A1: Hallo

A2: World

My goal is to merge the contents of A1

4条回答
  •  孤街浪徒
    2021-01-20 02:19

    Although, as MasterMix says, this is most easily achieved by a formula, if you have a reason why VBA must be used then it depends on how you wish to specify the cells.

    You could do this as a function:

    Private Function addTwoCells(rngA As Range, rngB As Range) As String
        addTwoCells = rngA & rngB
    End Function

    All this does is replicate the (much faster) built-in Excel concatenate function though.

    You could also do it in one of about a hundred ways in a procedure, here's one way that prompts the user for the ranges:

    Private Sub addTwoCellsProc()
        Dim rngA As String
        Dim rngB As String
        Dim rngOutput As String
        Dim rngTest As Range
    
        Do
            rngA = InputBox("Please enter first cell address", "Cell A")
            rngA = Range(rngA).Cells(1, 1).Address
            Set rngTest = Intersect(Range(rngA).Cells(1, 1), ActiveSheet.Cells)
        Loop Until Not rngTest Is Nothing
    
        Do
            rngB = InputBox("Please enter second cell address", "Cell B")
            rngB = Range(rngB).Cells(1, 1).Address
            Set rngTest = Intersect(Range(rngB), ActiveSheet.Cells)
        Loop Until Not rngTest Is Nothing
    
        Do
            rngOutput = InputBox("Please enter destination cell address", "Output cell")
            Set rngTest = Intersect(Range(rngOutput), ActiveSheet.Cells)
        Loop Until Not rngTest Is Nothing
    
        Range(rngOutput) = Range(rngA) & Range(rngB)
    End Sub

    You could also use predefined ranges and loop through them if you have multiple ranges to combine. If you explain a bit more about the scenario then someone might provide more specific code.

提交回复
热议问题