简体   繁体   中英

Move selection to their respective column's bottom in excel vba

If I have data in 5 columns (AF) and I select different cells within those columns, I'd like a macro that would move the contents of these cells to their respective columns 12th row.

Egs.: A3,B2,B4,C4,D1,D2,F4 The contents of these should go to A12,B12,C12,D12,F12 separated by a ", ".

This almost does the job, but it doesn't work if I select stuff from more than 1 column:

Sub Move()

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

Set selectedCells = Selection
ReDim values(selectedCells.Count - 1)

i = 0
For Each rng In selectedCells
    values(i) = CStr(rng.Value)
  i = i + 1
Next rng

CSV = Join(values, ", ")

Dim vArr
vArr = Split(Selection.Address(True, False), "$")
SC = vArr(0)

Range(SC & "12").Value = CSV
Selection.ClearContents

End Sub

Thanks for the help in advance!

The use of Selection is discouraged, but if you want to take that approach, what about something like this?

Sub Move()

Dim selectedCells As Range
Dim rng As Range
Dim targetRng As Range

Set selectedCells = Selection

For Each rng In selectedCells
    Set targetRng = Cells(12, rng.Column)
    If IsEmpty(targetRng) Then
        targetRng = rng
    Else
        targetRng = targetRng & ", " & rng
    End If
    rng.ClearContents
Next rng

End Sub

another possibility:

Sub Move()
    Dim cell As Range, cell2 As Range

    For Each cell In Selection
        With Cells(12, cell.Column)
            If IsEmpty(.Value) Then
                For Each cell2 In Intersect(.EntireColumn, Selection)
                    .Value = .Value & " " & cell2.Value
                Next
                .Value = Join(Split(Trim(.Value), " "), ",")
            End If
        End With
    Next
    Selection.ClearContents
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM