简体   繁体   English

在excel vba中将选择内容移到其相应列的底部

[英]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. 如果我在5列(AF)中有数据,并且在这些列中选择了不同的单元格,那么我想要一个宏,它将这些单元格的内容移到它们各自的第12行。

Egs.: A3,B2,B4,C4,D1,D2,F4 The contents of these should go to A12,B12,C12,D12,F12 separated by a ", ". 例如:A3,B2,B4,C4,D1,D2,F4这些内容应转到A12,B12,C12,D12,F12,并用“,”分隔。

This almost does the job, but it doesn't work if I select stuff from more than 1 column: 这几乎可以完成工作,但是如果我从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

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? 不鼓励使用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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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