有条件地移动列

时间:2015-06-24 20:06:32

标签: excel vba excel-vba

我有一系列我正在跟踪的拨款,其中一行是"状态",可以是"有效"或"无效"。当状态更改为" Inactive"时,我希望将该列复制到另一个标题为" Inactive"的工作表中。可以删除原件,也可以为活动授权创建另一张名为" Active"并且对于那些更容易的人进行相同的处理。

我试图修改我在互联网上找到的类似过程的一些代码,但我没有运气。大学里我的基础C +课程已经好几年了!我想这可能会更复杂,移动列而不是行,但这就是我需要的方式。

1 个答案:

答案 0 :(得分:1)

我已经纠正了你链接的代码。

首先,看看我原来的数据:

before1 before2

代码(将前4个注释行中的值更改为您需要的值):

Option Explicit

Sub Move_Inactive_to_Other_Sheet()
    Const sOrigSheet As String = "Sheet1"       'Name of the original sheet
    Const lStatusRow As Long = 2                'the # of row where you have Status in the original sheet
    Const sInactSheet As String = "inactive"    'Name of the sheet where inactive data is put
    Const lInactStartCol As Long = 2            'Column # in the Inactive data sheet where data starts to be put
    Dim lColCount As Long
    Dim c As Long
    Dim i As Long
    Dim Sh1 As Worksheet, Sh2 As Worksheet
    Set Sh1 = ThisWorkbook.Worksheets(sOrigSheet)
    Set Sh2 = ThisWorkbook.Worksheets(sInactSheet)

    lColCount = Range(Sh1.Cells(1, 1), Sh1.UsedRange).Rows.Count
    i = lInactStartCol
    For c = 1 To lColCount
        If Sh1.Cells(lStatusRow, c).Value = "inactive" Then
            Sh1.Columns(c).Copy Destination:=Sh2.Columns(i)
            Sh1.Columns(c).EntireColumn.Delete
            c = c - 1
            i = i + 1
        End If
    Next
    Sh2.Activate
End Sub

运行代码后的结果:

after1 after2