[英]Move selection to their respective column's bottom in excel vba
如果我在5列(AF)中有数据,并且在这些列中选择了不同的单元格,那么我想要一个宏,它将这些单元格的内容移到它们各自的第12行。
例如: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
我在这里先向您的帮助表示感谢!
不鼓励使用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
另一种可能性:
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.