且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Excel中使用VBA将2个单元格的内容合并到另一个第三个单元格中

更新时间:2023-01-31 12:13:56

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.

相关阅读

技术问答最新文章