基本上我有一列文本,如果单元格有文本,我想将下面的单元格移到右边。这听起来可能是胡说八道,所以请看下面的图片我想要的效果。非常感谢你。
答案 0 :(得分:1)
一般来说,这确实不是一个很好的问题as it fails the rules of StackOverflow,但是,这仍然是一个可能的答案,产生了这个输出:
Public Sub TestMe()
Dim myCell As Range
Dim currentCell As Range: Set currentCell = Range("D1")
Dim rangeToWrite As Range: Set rangeToWrite = Columns("D:E")
Dim lastRow As Long: lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Dim myRng As Range: Set myRng = Range(Cells(1, 1), Cells(lastRow, 1))
Dim stayLeft As Boolean: stayLeft = True
rangeToWrite.Clear
For Each myCell In myRng
If Len(myCell) Then
If stayLeft Then
stayLeft = False
If currentCell.Address <> Range("D1").Address Then
Set currentCell = currentCell.Offset(1, -1)
End If
currentCell = myCell
Else
Set currentCell = currentCell.Offset(0, 1)
With rangeToWrite
If currentCell.Column > .Columns(.Columns.Count).Column Then
Set currentCell = currentCell.Offset(0, -1)
currentCell = currentCell & vbCrLf & myCell
Else
currentCell = myCell
End If
End With
End If
Else
stayLeft = True
End If
Next myCell
End Sub
代码非常“棘手”(或令人讨厌),但它确实有效。像rangeToWrite.Columns(rangeToWrite.Columns.Count).Column
这样的东西可以让很多VBA开发者开始讨厌VBA。
代码的作用是什么?
ActiveSheet
; stayLeft
更新为false。这意味着下一个值将写在Range("D:E")
; 按 F8 ,看起来比解释更容易!