如何在excel vba中用逗号将选定的单元格合并到一个单元格中?

时间:2012-04-07 17:13:35

标签: excel vba excel-vba

如何将选定细胞中的细胞合并为一个细胞,选择的细胞数量会有所不同,可能是5个细胞或更多,但所有细胞都会像A1,A2,A3等一样继续。 我已经完成了这篇文章 Combine multiple cells into one in excel with macro? 但我如何使用上面提到的选定单元格的链接答案。我正在使用Excel 2007,所以我希望它是可压缩的代码。

3 个答案:

答案 0 :(得分:1)

只需尝试以下代码复制,粘贴并保存。 ||||||||||||

Required Data   Result     Code
1            1,2,3,4,5,    =darksider_con(A1:A5)
2       
3       
4       
5       

Function darksider_con(rng As range) As String
Dim cell As range
Dim result As String
For Each cell In rng
result = result & cell.Value & ","
Next
darksider_con = result
End Function

答案 1 :(得分:0)

我认为这应该可以解决问题。它基本上使用范围变量来处理选择。然后,它使用所选单元格的值填充数组。 CSV是可变的,包含您的结果。

请注意,selectedCells是一个变量,而不是Excel中的某些特殊功能。

[此代码在Excel 2002中有效 - 在其他版本上不确定。]

Dim selectedCells As Range
Dim rng As Range
Dim i As Integer
Dim values() As String
Dim CSV As String

' you may need some error handling here in case your selection
' isn't a range
Set selectedCells = Selection

ReDim values(selectedCells.Count - 1)

i = 0
For Each rng In selectedCells
  ' you may want some error handling here when populating the array
  values(i) = CStr(rng.Value)
  i = i + 1
Next rng

CSV = Join(values, ",")

答案 2 :(得分:0)

用于1D或2D范围。可以应用于包含空白单元格的范围。我们还可以分配一个快捷键Ctrl+Shift+M,就像MS Word中合并表中单元格的快捷键是Alt+M

警告。。宏结果无法撤消。因此,首先尝试对示例数据使用此宏。但是,如果在相同的合并范围上运行且值 MergeCellsWithComma :{{1},则可以在第二个过程restoreMergedCells撤消该Public variable宏的结果。 }不变。

确保两个过程中的valRngrowDelimiter相同。

cellDelimiter

为行创建不同的分隔符的想法:如果出现任何问题,我们应该能够使用以下过程来还原合并的单元格。如果在运行此过程之前更改了 Public valRng As String '______________________________________________________________ Sub MergeCellsWithComma() If Selection.MergeCells = True Then Exit Sub Application.DisplayAlerts = False rowDelimiter = "}" cellDelimiter = "|" Dim rng As Range: Set rng = Selection If rng Is Nothing Then Exit Sub On Error GoTo 0 Dim cL As Range valRng = "" For i = 1 To rng.Rows.Count For Each cL In Application.Index(rng, i, 0) 'If cL <> "" Then valRng = valRng & cL & cellDelimiter 'We can remove this if condition and keep only valRng = valRng & cL & cellDelimiter 'in case we want the resulting string to show blank cells as well. 'It would be better to do so if 'the original data needs to be restored Next 'Following is a separate delimiter for rows in the selection. 'If not needed comment it valRng = Left(valRng, Len(valRng) - 1) & rowDelimiter ' instead of rowDelimiter one can use Chr(10) for line break Next valRng = Left(valRng, Len(valRng) - 1) rng.MergeCells = True Range(rng(1, 1).Address) = valRng Application.DisplayAlerts = True End Sub 的值:Public variable,则将其分配给valRng

valRng = Selection.Cells(1, 1).Value