2009-11-12 98 views
0

我有excel宏选择一行来剪切和粘贴到下一张表。现在,我想一次选择多行来剪切并粘贴到下一张纸张,然后返回到上一张纸张以删除被剪切的空白行。我对单排剪切和粘贴的代码如下:excel宏选择多行

Sub CutPasteRows() 
Dim iLastRow As Integer 


    'select the first cell to intiate script 
    txtRowNum = Selection.Row 
    'select the row 
    Rows(txtRowNum).EntireRow.Select 
    Selection.Cut 

    'if the active worksheet is the last one (no next worksheet), display error. 
    If ActiveSheet.Index = Worksheets.Count Then 
     MsgBox ("There are no next worksheet") 
    Else 
     ActiveSheet.Next.Select 
     iLastRow = ActiveSheet.UsedRange.Rows.Count 

     'if the workshet is blank, start with the first row. Otherwise, add 1 to the last row 
     If Cells(1, 1).Value = "" And iLastRow = 1 Then 
      iLastRow = 1 
     Else 
      iLastRow = iLastRow + 1 
     End If 

     'Paste row 
     Rows(iLastRow).EntireRow.Select 
     ActiveSheet.Paste 

     'Go back to the last worksheet 
     ActiveSheet.Previous.Select 
     Rows(txtRowNum).EntireRow.Select 
     Selection.Delete 
    End If 
End Sub 

任何帮助表示赞赏。

谢谢

+0

什么是你的问题? – 2009-11-12 22:23:18

+0

它做错了什么?什么是错误信息或问题? – 2009-11-12 22:23:58

回答

0

你只需要联合你所需要的行。

像这样:

Set workingRange = Application.Union(workingRange, newRange) 

当然,这意味着使用范围的对象,而不是行号。

1

如果您一次选择多行,则Selection属性将返回一个Range对象。使用这个Range对象,您应该能够将选定的行剪切并粘贴到下一个工作表中,然后从之前的工作表中删除它们。

我做了一个快速改变你的代码,我觉得应该让你开始在正确的道路上:

Sub CutPasteRows() 
Dim iLastRow As Integer 

'Cut entire selection' 
Selection.Cut 

'if the active worksheet is the last one (no next worksheet), display error.' 
    If ActiveSheet.Index = Worksheets.Count Then 
    MsgBox ("There are no next worksheet") 
    Else 
    ActiveSheet.Next.Select 
    iLastRow = ActiveSheet.UsedRange.Rows.Count 

    'if the worksheet is blank, start with the first row. Otherwise, add 1 to the last row' 
    If Cells(1, 1).Value = "" And iLastRow = 1 Then 
     iLastRow = 1 
    Else 
     iLastRow = iLastRow + 1 
    End If 

    'Paste row' 
    Rows(iLastRow).EntireRow.Select 
    ActiveSheet.Paste 

    'Go back to the last worksheet and delete selection' 
    ActiveSheet.Previous.Select 
    Selection.Delete 
End If 

Selection property

Range object