我有一个从L列到AA列的数据集。我希望所有单元格都移动,这样每一行中的最后一个单元格就会移动到AA列,其余单元格就会向右移动,这样所有空白单元格都会消失。有人能帮我写一段VBA代码吗?谢谢!
Option Explicit
Sub main()
Dim rng As Range, cell As Range
Dim lastCol As Long, maxCol As Long, iCol As Long
With Worksheets("Align") '<--| change "Align" to your actual sheet name
Set rng = .Range("A1", .Cells(.Rows.Count, 1).End(xlUp)).SpecialCells(XlCellType.xlCellTypeConstants) '<--| get all columns "A" not empty cells
ReDim lastCols(1 To rng.Count) As Long '<--| resize last column index array accordingly to the number of not empty cells
For Each cell In rng '<--| loop through column "A" not empty cells
iCol = iCol + 1 '<--| update last column index array index
lastCols(iCol) = .Cells(cell.row, .Columns.Count).End(xlToLeft).Column '<--| update last column index array current index value
If lastCols(iCol) > maxCol Then maxCol = lastCols(iCol) '<--| update maximum column index
Next cell
iCol = 1 '<--| initialize last column index array index
For Each cell In rng '<--| loop through column "A" not empty cells
If lastCols(iCol) < maxCol And lastCols(iCol) > 3 Then cell.Offset(, lastCols(iCol) - 3).Resize(, maxCol - lastCols(iCol)).Insert xlShiftToRight '<--| if current cell row has at least three not empty cells and the last one has smaller column index than maximum column index then shift current cell row last three cells to align left with maximum column index
iCol = iCol + 1
Next cell
End With
End Sub
https://stackoverflow.com/questions/51858999
复制相似问题