首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >需要对齐数据并消除空白

需要对齐数据并消除空白
EN

Stack Overflow用户
提问于 2018-08-15 20:47:08
回答 1查看 42关注 0票数 -1

我有一个从L列到AA列的数据集。我希望所有单元格都移动,这样每一行中的最后一个单元格就会移动到AA列,其余单元格就会向右移动,这样所有空白单元格都会消失。有人能帮我写一段VBA代码吗?谢谢!

代码语言:javascript
运行
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51858999

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档