在Excel中使用VBA将2个单元格的内容合并到另一个第三个单元格中 [英] Merge the contents of 2 cells into another 3rd cell using VBA in Excel
问题描述
我有两个单元格可以说:A1和A2
每个单元格的内容是一个字符串:
A1:Hallo
A2:世界
我的目标是合并A1和A2在另一个单元格例如A3,A3的内容应该是:
Hallo World
我想使用VBA宏和
感谢你们的答案!!
你可以这样做:
私有函数addTwoCells(rngA As Range,rngB As Range)As String
addTwoCells = rngA&rngB
结束功能
所有这一切都是复制(更快)内置的Excel连接功能。
您也可以在程序中以百种方式之一进行操作,这里提供用户范围的一种方法:
Private Sub addTwoCellsProc()
Dim rngA As String
Dim rngB As String
Dim rngOutput As String
Dim rngTest As Range
Do
rngA = InputBox(请输入第一个单元格地址,单元格A)
rngA =范围( rngA).Cells(1,1).Address
设置rngTest = Intersect(Range(rngA).Cells(1,1),ActiveSheet.Cells)
循环直到不是rngTest没有
Do
rngB = InputBox(请输入第二个单元格地址,单元格B)
rngB =范围(rngB).Cells(1,1).Address
设置rngTest = Intersect(Range(rngB),ActiveSheet.Cells)
循环直到不是rngTest没有
rngOutput = InputBox(请输入目标单元格地址,输出单元格)
设置rngTest = Intersect(Range(rngOutput),ActiveSheet.Cells)
循环直到不是rngTest没有
范围(rngOutput)=范围(rngA)和范围(rngB)
End Sub
如果您有多个范围组合,您还可以使用预定义的范围并循环使用它们。如果您更多地解释了这种情况,那么有人可能会提供更具体的代码。
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 and A2 in another cell e.g. A3 i.e. A3's content should be:
Hallo World
I would like to do this using a VBA macro and not only for strings as contents..
Thanks both of u for your answers!!
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.
这篇关于在Excel中使用VBA将2个单元格的内容合并到另一个第三个单元格中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!