我有两个单元格可以说:A1和A2
每一个的内容都是一个字符串:
A1:你好
A2:世界
我的目标是将A1和A2的内容合并到另一个小区中,例如A3即A3的内容应为:
你好世界
我想使用VBA宏执行此操作,而不仅仅是将字符串作为内容..
感谢你们的回答!!
答案 0 :(得分:6)
虽然,正如MasterMix所说,这最容易通过公式实现,如果你有必要使用VBA的原因,那么它取决于你希望如何指定单元格。
你可以这样做:
Private Function addTwoCells(rngA As Range, rngB As Range) As String addTwoCells = rngA & rngB End Function
所有这些都会复制(更快)内置的Excel连接函数。
您也可以在程序中以大约一百种方式之一进行,这是提示用户输入范围的一种方式:
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
如果要组合多个范围,也可以使用预定义范围并循环显示它们。如果您对该场景有更多解释,那么有人可能会提供更具体的代码。
答案 1 :(得分:3)
我建议使用Excel公式
=A1&A2
或VBA宏
Range("A3").Cell.Value = Range("A1").Cell.Value & Range("A2").Cell.Value
答案 2 :(得分:0)
这个更快,只需选择单元格并将它们合并到第一个单元格中。
'------------------------------------------------------------------------
' Procedure : Concatenate Text
' Author : Tim Bennett
' Date : 11/6/2015
' Purpose : Concatenate selected text into first column
'------------------------------------------------------------------------
'
'Sub Concatenate_Formula(bConcat As Boolean, bOptions As Boolean)
Sub Concatenate()
Dim rSelected As Range
Dim c As Range
Dim sArgs As String
Dim bCol As Boolean
Dim bRow As Boolean
'Set variables
Set rOutput = ActiveCell
bCol = False
bRow = False
On Error Resume Next
'Use current selection
Set rSelected = Selection
On Error GoTo 0
'Only run if cells were selected and cancel button was not pressed
If Not rSelected Is Nothing Then
sArgs = "" 'Create string of cell values
firstcell = ""
For Each c In rSelected.Cells
If firstcell = "" Then firstcell = c.Address(bRow, bCol)
sArgs = sArgs + c.Text + " " 'build string from cell text values
c.Value = "" ' Clear out the cells taken from
Next
'Put the result in the first cell
Range(firstcell).Value = sArgs
End If
End Sub
答案 3 :(得分:0)
在更一般的情况下,这是一个连接任意数量的单元格的宏(甚至是非相邻的单元格块)注意:我没有包含检查用户取消的代码。
Sub G()
Dim strFinal$
Dim cell As Range
Dim rngSource As Range
Dim rngArea As Range
Dim rngTarget As Range
Set rngSource = Application.InputBox("Select cells to merge", Type:=8)
Set rngTarget = Application.InputBox("Select destination cell", Type:=8)
For Each rngArea In rngSource
For Each cell In rngArea
strFinal = strFinal & cell.Value & " "
Next
Next
strFinal = Left$(strFinal, Len(strFinal) - 1)
rngTarget.Value = strFinal
End Sub