将选择移动到excel vba中各自列的底部

时间:2018-04-28 18:22:35

标签: excel vba selection move

如果我有5列(A-F)中的数据,并且我在这些列中选择了不同的单元格,我想要一个将这些单元格的内容移动到各自列的第12行的宏。

Egs。:A3,B2,B4,C4,D1,D2,F4 这些内容应转到A12,B12,C12,D12,F12,由","分隔。

这几乎可以完成这项工作,但是如果我选择超过1列的内容,它就无法运作:

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

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

不鼓励使用Selection,但如果你想采取这种方法,那么这样的事情呢?

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

答案 1 :(得分:0)

另一种可能性:

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