使用宏将多个单元格合并为一个excel?

时间:2010-01-18 22:45:40

标签: excel vba

我对此问题提出了类似的问题:

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

但我想在一列中组合一系列细胞,例如A2:A50。有时我有超过300个细胞合并为一个。值是文本。有没有办法修改这个宏,以便它可以在一个范围而不仅仅是两个单元格上工作?

谢谢!

3 个答案:

答案 0 :(得分:5)

基于the thread you are citing,我想您希望返回单元格所有值的连接,将所有值解释为字符串?

为此,您可以使用如下所示的VBA宏:

Function ConcatinateAllCellValuesInRange(sourceRange As Excel.Range) As String
    Dim finalValue As String

    Dim cell As Excel.Range

    For Each cell In sourceRange.Cells
        finalValue = finalValue + CStr(cell.Value)
    Next cell

    ConcatinateAllCellValuesInRange = finalValue
End Function

例如,您可以这样称呼它:

Sub MyMacro()
    MsgBox ConcatinateAllCellValuesInRange([A1:C3])
End Sub

这是你在找什么?

麦克

答案 1 :(得分:4)

尝试下面的宏,不是很优雅,因为它没有做任何错误检查等但是有效。将宏分配给按钮,单击单元格,单击宏按钮,使用鼠标突出显示要合并的所需(源)范围(将在对话框的输入框中自动填充范围),单击确定,突出显示目标单元格(将在下一个对话框中自动填充输入框)单击确定,所有单元格将与单个空格字符合并到目标单元格中​​,该单元格可以位于原始源范围内)。由您自己手动删除多余的单元格。包含行和列但不包含块的工作区。

Sub JoinCells()

Set xJoinRange = Application.InputBox(prompt:="Highlight source cells to merge",    Type:=8)
xSource = 0
xSource = xJoinRange.Rows.Count
xType = "rows"
If xSource = 1 Then
    xSource = xJoinRange.Columns.Count
    xType = "columns"
End If
Set xDestination = Application.InputBox(prompt:="Highlight destination cell", Type:=8)
If xType = "rows" Then
    temp = xJoinRange.Rows(1).Value
    For i = 2 To xSource
        temp = temp & " " & xJoinRange.Rows(i).Value
    Next i
Else
    temp = xJoinRange.Columns(1).Value
    For i = 2 To xSource
        temp = temp & " " & xJoinRange.Columns(i).Value
    Next i
End If

xDestination.Value = temp

End Sub

答案 2 :(得分:0)

只是要添加到Mike的解决方案中,如果你想从变量而不是定义范围中获取范围(我的语法有问题):

Sub MyMacro()

dim myVar As Range

    MsgBox ConcatinateAllCellValuesInRange(myVar)

End Sub
相关问题