[英]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.