VB excel宏代码删除工作表中的列数据并插入其他工作表并列出空列

时间:2016-06-08 21:03:08

标签: excel vba macros

我的代码存在问题。我有一个excel表 a ,有7列。我想要复制并添加所选/突出显示的行的前5列,并将它们添加到工作表 b 的第一个空行,并在按下更新按钮的同时删除剩余的2列:< / p>

Sub Macro1()
'
' Macro1 Macro
'

'
    Range("F:G").Select
    Range("A:E").Select
    Selection.Cut
    Sheets("Instock").Select
    Range("A280").Select
    ActiveSheet.Paste
    Cells.Select
    Range("A256").Activate
    ActiveWorkbook.Worksheets("Instock").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Instock").Sort.SortFields.Add Key:=Range( _
        "B2:B4096"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortNormal
    ActiveWorkbook.Worksheets("Instock").Sort.SortFields.Add Key:=Range( _
        "A2:A4096"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortNormal
    With ActiveWorkbook.Worksheets("Instock").Sort
        .SetRange Range("A1:G4096")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Sheets("Checked Out").Select
    Rows("3:3").Select
    Selection.Delete Shift:=xlUp
    Range("H17").Select
End Sub

1 个答案:

答案 0 :(得分:0)

从我收集的内容中,您有2个工作表

  • INSTOCK
  • 签出

当您按下更新时,您想要:

  • 将[Checked Out]中所选行的前5列值添加到[Instock]
  • 清除[Checked Out]
  • 中所选行的第6列和第7列中的值
  • 排序[Instock]

试试这个:

Public Sub MoveStockItems()
    If Not (ActiveSheet.Name = "Checked Out") Then Exit Sub
    Dim newRow As Long, rw As Long

    rw = ActiveCell.Row
    With Sheets("Instock")
        newRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
        .Cells(newRow, 1) = Cells(rw, 1)
        .Cells(newRow, 2) = Cells(rw, 2)
        .Cells(newRow, 3) = Cells(rw, 3)
        .Cells(newRow, 4) = Cells(rw, 4)
        .Cells(newRow, 5) = Cells(rw, 5)
        Cells(rw, 6) = ""
        Cells(rw, 7) = ""
    End With
    Call SortInstock
End Sub

Public Sub SortInstock()
    Dim rowCount As Long
    With Worksheets("Instock")
         rowCount = .UsedRange.Rows.Count
        .Sort.SortFields.Clear
        .Sort.SortFields.Add Key:=.Range("B2:B" & rowCount), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        .Sort.SortFields.Add Key:=.Range("A2:A" & rowCount), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    End With

    With Worksheets("Instock").Sort
        .SetRange Worksheets("Instock").UsedRange
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

将此代码粘贴到代码模块中,然后为MoveStockItems分配快捷键。

用法:在[Checked Out]上选择一个单元格,按快捷键k运行宏。