2016-06-23 66 views
0

我需要根據特定條件將行移動到新工作表。我在這裏發現了一個非常有用的討論,它幾乎正是我需要的,但是這些行需要從主表中刪除。我一直在使用的代碼是這樣的:將行按照特定條件剪切/粘貼到新工作表

Option Explicit 

Sub Fr33M4cro() 

Dim sh33tName As String 
Dim custNameColumn As String 
Dim i As Long 
Dim stRow As Long 
Dim customer As String 
Dim ws As Worksheet 
Dim sheetExist As Boolean 
Dim sh As Worksheet 

sh33tName = "Sheet1" 
custNameColumn = "I" 
stRow = 2 

Set sh = Sheets(sh33tName) 

For i = stRow To sh.Range(custNameColumn & Rows.Count).End(xlUp).Row 
    customer = sh.Range(custNameColumn & i).Value 
    For Each ws In ThisWorkbook.Sheets 
     If StrComp(ws.Name, customer, vbTextCompare) = 0 Then 
      sheetExist = True 
      Exit For 
     End If 
    Next 
    If sheetExist Then 
     CopyRow i, sh, ws, custNameColumn 
    Else 
     InsertSheet customer 
     Set ws = Sheets(Worksheets.Count) 
     CopyRow i, sh, ws, custNameColumn 
    End If 
    Reset sheetExist 
Next i 

End Sub 

Private Sub CopyRow(i As Long, ByRef sh As Worksheet, ByRef ws As Worksheet, custNameColumn As String) 
Dim wsRow As Long 
wsRow = ws.Range(custNameColumn & Rows.Count).End(xlUp).Row + 1 
sh.Rows(i & ":" & i).Copy 
ws.Rows(wsRow & ":" & wsRow).PasteSpecial _ 
Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False 
Application.CutCopyMode = False 
End Sub 

Private Sub Reset(ByRef x As Boolean) 
x = False 
End Sub 

Private Sub InsertSheet(shName As String) 
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = shName 
End Sub 

任何見解都會有幫助,因爲我對此很新穎。謝謝!在Rows.Count前面的ws.

回答

0

試試這個:

Private Sub CopyRow(i As Long, ByRef sh As Worksheet, ByRef ws As Worksheet, custNameColumn As String) 
Dim wsRow As Long 
wsRow = ws.Range(custNameColumn & ws.Rows.Count).End(xlUp).Row + 1 

ws.Rows(wsRow).EntireRow.Value = sh.Rows(i).EntireRow.Value 
sh.Rows(i).EntireRow.Delete 
End Sub 

注意。此外,由於您只需要值,因此您可以將範圍設置爲等於彼此。這樣,你繞過了剪貼板,它有點快。

注:因爲你要被刪除行,在調用此子循環,我建議開始在年底和向頂部工作的方式:

For i = sh.Range(custNameColumn & sh.Rows.Count).End(xlUp).Row to stRow Step -1

那應該管用。否則,將i = i - 1添加到CopyRow子的末尾,並使i全局。

如果你只想要列A-M(1〜13),你會做:

ws.Range(ws.cells(i,1),ws.cells(i,13)).Value = sh.Range(sh.Cells(i,1),sh.Cells(i,13)).Value

(我可能有一個向後,或i切換,但你應該明白我的意思)。

+0

非常感謝! –

+0

我該如何編輯這個只是剪切/粘貼列A-M的值? –

+0

@ A.Newt - 看我的編輯。 – BruceWayne

相關問題