用于根据条件移动行的VBA代码

时间:2015-12-23 10:07:01

标签: excel vba excel-vba

我是StackExchange和VBA的新手,我试图找到答案,但我遇到了问题!!!

我有一个电子表格,其中输入信息并显示在表2的B-I栏中。我想要做的是,如果H列是空白的,它会将整行移动到L列到S列。因此,根据H是空还是填充,我的数据将被分成同一张纸上的2个独立位置。 / p>

H列中的信息每次都不同,因此我无法指定列中的内容,但有时候H列中没有任何内容输入,而我希望它移动

谁能告诉我如何实现这一目标? 非常感谢 BEV

2 个答案:

答案 0 :(得分:1)

尝试这个作为起点

Option Explicit
Const FIRST_ROW As Long = 2
Const LAST_ROW As Long = 100
Const FIRST_SOURCE_COL As Long = 2 'column B
Const LAST_SOURCE_COL As Long = 9 'column I
Const TRIG_COL As Long = 8 'column H
Const GAP As Long = 2 'columns gap between original data and moved data

Sub moveit()
Dim r As Long
Dim c As Long
Const DIST As Long = LAST_SOURCE_COL - FIRST_SOURCE_COL + GAP + 1

For r = FIRST_ROW To LAST_ROW
    'check if we need to move
    If Cells(r, TRIG_COL).Value = "" Then
    'move the data
        For c = FIRST_SOURCE_COL To LAST_SOURCE_COL
            Cells(r, c + DIST).Value = Cells(r, c).Value
            Cells(r, c).Value = ""
        Next
    End If
Next
End Sub

答案 1 :(得分:1)

移动空白,

Sub MoveBlanks()
    Dim lRws As Long, sh As Worksheet, x

    Set sh = Sheets("Sheet2")

    With sh
        lRws = .Cells(.Rows.Count, "B").End(xlUp).Row
        For x = lRws To 2 Step -1
            If .Cells(x, "H") = "" Then
                .Range(.Cells(x, "B"), .Cells(x, "I")).Cut .Cells(.Rows.Count, "L").End(xlUp).Offset(1)
                .Range(.Cells(x, "B"), .Cells(x, "I")).Delete Shift:=xlUp
            End If
        Next x
    End With

End Sub

<强>之前

enter image description here

<强>后 enter image description here