宏将多个单元格合并为一个,其中的值用逗号分隔

时间:2013-08-28 17:27:31

标签: vba excel-2007

在之前发布的答案Combine multiple cells into one in excel with macro?中,提供了以下宏...顺便说一下,它的效果很好!

但是,我需要用逗号分隔单元格值。我试过在引号“,”之间插入一个逗号,但这不起作用。有人可以指导我,以便生成的单元格将用逗号分隔值吗?谢谢!

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 :(得分:1)

看看这里: http://www.excelforum.com/tips-and-tutorials/860240-concatall-udf-by-tigeravatar.html

第一篇文章展示了如何使用它,第8篇文章是最新版本。

[编辑] 或者,只需将& " " &的两个实例更改为& "," &

答案 1 :(得分:0)

这是我用来做这个的功能。它仅适用于单个列,但如果需要,可以很容易地适用于多个列。

Function CommaList(DataRange As Range, Optional Seperator As String = ",", Optional Quotes As Boolean = True) As String
    Dim iCellNum As Integer
    Dim sTemp As String

    If DataRange.Columns.Count > 1 Then
        CommaList = "Select a Single Column"
        Exit Function
    End If

    For iCellNum = 1 To DataRange.Cells.Count
        If Quotes Then
            sTemp = sTemp + "'" + DataRange.Cells(iCellNum, 1) + "'"
        Else
            sTemp = sTemp + DataRange.Cells(iCellNum, 1)
        End If
        If iCellNum < DataRange.Cells.Count Then
            sTemp = sTemp + Seperator
        End If
    Next iCellNum

    CommaList = sTemp

End Function