0

I have Range(one dimensional), that I want to summarize in one cell by concatenating all values. I thought that I could do just:

Dim Data_array()
Dim Source_Range as Range

Set Source_Range = Selection
Data_array() = Source_Range.Value2
Source_range.Offset( -1 ,0).Value = Join(Data_array, ", ")

This however returns error 5 because Data_array is a ( 1 To X, 1 To 1) array it has two dimensions, and Join on last line requires that you provide just one dimenstional array.

So my question would be is there a way to remove that "1 To 1" dimension?
If not how would you concatenate a one dimensional range in one cell.

Example

     A
1    
2    2
3    4
4    6

Desired Result

     A
1    2, 4, 6
2    2
3    4
4    6
sgp667
  • 1,797
  • 2
  • 20
  • 38

4 Answers4

2

You were so close! The code below assumes you will select the cells below the empty target cell. I't is simply two tweaks from your original code:

Sub testing()

    Dim Data_array()
    Dim Source_Range As Range

    Set Source_Range = Selection
    Data_array() = WorksheetFunction.Transpose(Source_Range.Value2)
    Source_Range.Offset(-1, 0).Resize(1, 1).Value = Join(Data_array, ", ")

End Sub
tbur
  • 2,384
  • 1
  • 13
  • 12
1

For your data, I would not bother with a VBA array. Consider:

Public Function Konkat(rin As Range) As String
    For Each r In rin
        v = r.Value
        If v <> "" Then
            Konkat = Konkat & "," & v
        End If
    Next r
    Konkat = Right(Konkat, Len(Konkat) - 1)
End Function

enter image description here

This is because in your code, data_Array is actually a two-dimensional array.

Gary's Student
  • 95,722
  • 10
  • 59
  • 99
1

Below is an idea. NOTE: I'm not sure that the OFFSET part of your code does what you want it to do. Test the code, and let me know if so.

Dim Data_array()
Dim Source_Range As Range
Dim nIncrement As Integer

Set Source_Range = Selection
nIncrement = 1

ReDim Data_array(1 To Source_Range.Rows.Count)
For Each cel In Source_Range
    Data_array(nIncrement) = cel.Value
    nIncrement = nIncrement + 1
Next cel

Source_Range.Offset(-1, 0).Value = Join(Data_array, ", ")
basodre
  • 5,720
  • 1
  • 15
  • 23
1

You can use the INDEX worksheet function to slice out a column or row.

Sub JoinRangeComma()

    Dim vaData As Variant
    Dim rSource As Range
    Dim wf As WorksheetFunction

    Set wf = Application.WorksheetFunction
    Set rSource = Selection
    vaData = rSource.Value2
    rSource.Cells(1).Offset(-1, 0).Value = Join(wf.Index(wf.Transpose(vaData), 1, 0), ", ")

End Sub
Dick Kusleika
  • 32,673
  • 4
  • 52
  • 73