2009-11-12 97 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