如果我将光标放在第1行,那么除了行值之外我希望所有行都连接起来。接下来,如果我将光标放在第二行,那么除了那行我需要连接所有行之外,这将是n
行数。
Sub concatenate()
Dim x As String
Dim Y As String
For Q = 1 To 1 'This provides a column reference to concatenate - Outer For statement
For T = 1 To 24 'This provides a rows reference to concatenate - Inner for statement
For Each cell In Cells(T, Q) 'provides rows and column reference
Set rng = Range("A1", "A20")
If cell.Value = "" Then GoTo Line1 'this tells the macro to continue until a blank cell is reached
x = x & "*" & "~" & cell.Value 'This provides the concatenated cell value and comma separator
Next ' this loops the range
Next T 'This is the inner loop which dynamically changes the number of rows to loop until a blank cell is reached
Line1:
On Error GoTo Terminate 'Terminates if there are less columns (max 10) to concatenate
ActiveCell.Value = Mid(x, 7, Len(x) - 1) 'This basically removes the last comma from the last concatenated cell e.g. you might get for a range 2,3,4, << this formula removes the last comma to
'give 2,3,4
ActiveCell.Offset(1, 0).Select 'Once the concatenated result is pasted into the cell this moves down to the next cell, e.g. from F1 to F2
x = "" 'The all important, clears x value after finishing concatenation for a range before moving on to another column and range
Next Q 'After one range is done the second column loop kicks in to tell the macro to move to the next column and begin concatenation range again
Terminate: 'error handler
End Sub