VBA如何在不影响其自身列Excel的情况下向左移动单元格

问题描述 投票:-2回答:1
COLS : NO |   | B | C |   | D
  01 : 1  |   | 8 | 3 |   | 2
  02 :    |   |   | 4 |   | 
  03 :    |   |   |   |   |
  04 : 2  |   | 5 | 2 |   | 6

如何将值向左移动并删除空行,但将值保留在其自己的列中?目标是:

COLS : NO | B | C | D
  01 : 1  | 8 | 3 | 2
  02 :    |   | 4 | 
  03 : 2  | 5 | 2 | 6
  04 :    |   |   |

C2中的数字4应该保留在其自己的列中(这是C列中记录1的额外值)。我现在得到的不是我想要的:

COLS : NO | B | C | D
  01 : 1  | 8 | 3 | 2
  02 : 4  |   |   | 
  03 : 2  | 5 | 2 | 6
  04 :    |   |   |
excel vba macros cell
1个回答
0
投票

尝试

Sub test()
    Dim Ws As Worksheet
    Dim rngDB As Range, rng As Range
    Dim vDB As Variant, vR() As Variant
    Dim i As Long, r As Long
    Dim n As Long, c As Integer, j As Integer
    Dim k As Integer

    Set Ws = ActiveSheet
    Set rngDB = Ws.UsedRange
    vDB = rngDB
    r = UBound(vDB, 1)
    c = UBound(vDB, 2)
    ReDim vR(1 To r, 1 To c)
    For i = 1 To r
        Set rng = rngDB.Rows(i)
        If WorksheetFunction.CountA(rng) Then
            n = n + 1
            k = 0
            For j = 1 To c
                If vDB(i, j) <> "" Then
                    k = k + 1
                    vR(n, k) = vDB(i, j)
                End If
            Next j
        End If
    Next i
    'rngDB = vR  '<~~~  Use this to write on the same sheet.
    Sheets.Add
    Range("a1").Resize(r, c) = vR
End Sub

之前

enter image description here

之后

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.