2017-06-29 44 views
0

代碼中沒有錯誤。
但我沒有得到我想要的東西。VBA:未能將最後一行填入表格(數組表格)

該代碼應該採取每個行中有「總計」,然後粘貼它填充表。
但是,我目前得到的所有表都是錯誤的,有些甚至複製了沒有「Total」的行。
對某些人來說,應該只有15行,但它提供了30

For Each name In Array("Sheet A", "Sheet B", _ 
"Sheet C", "Sheet D") 
     Set ws = ThisWorkbook.Worksheets(name) 
    'find EVERY total row then copy the range from A-J 
    'new rows with contents added during macro run 
     ws.Columns("L:U").Select 
     Selection.ClearContents 

     For Each cell In Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row) 
      If cell.Value = "Total" Then 
       cell.Activate 
       n = ActiveCell.Row 

      Set rnge = Range(ws.Cells(n, 1), ws.Cells(n, 10)) 
      rnge.Copy 

     'clear contents before contents paste to here 
     'it was kinda unnecessary but im clueless on how to only copy new added row 
     'and paste them to create new table (in same sheet from columnL) 
     'Columns("L:U").Select 
     'Selection.ClearContents 

      pasteRow = ws.Cells(ws.Rows.Count, "L").End(xlUp).Row + 1 
      ws.Cells(pasteRow, "L").PasteSpecial xlPasteValues 

      End If 
     Next cell 
Next name 

我還是新的,所以我也不太清楚,如果這是因爲片陣列或範圍/中使用了錯誤的細胞。
我做了這個假設,因爲當我運行這個,在單張上,它工作正常。

For Each ws In ThisWorkbook.Worksheets 
    If ws.Name = "Sheet A" Then 
+1

'Range'隱式地使用'ActiveSheet'。 – ThunderFrame

+1

研究如何擺脫.select並着眼於完全限定您的參考。那應該讓你達到99%+的方式。 – sous2817

回答

0

您的問題是Explicitly referencing你的對象。
起初,你做了正確的事情設置ws變量,但未能保持一致。嘗試:

Dim ws As Worksheet, cell As Range, rnge As Range 

For Each Name In Array("Sheet A", "Sheet B", _ 
         "Sheet C", "Sheet D") 
    Set ws = ThisWorkbook.Worksheets(Name) 

    With ws '/* reference all Range call to your worksheet */ 
     .Columns("L:U").ClearContents '/* abandon use of Select */ 
     For Each cell In .Range("A1:A" & .Range("A" & .Rows.Count).End(xlUp).Row) 

      If cell.Value = "Total" Then 
       n = cell.Row 

       Set rnge = .Range(.Cells(n, 1), .Cells(n, 10)) 
       rnge.Copy 

       pasteRow = .Cells(.Rows.Count, "L").End(xlUp).Row + 1 
       .Cells(pasteRow, "L").PasteSpecial xlPasteValues 

      End If 

     Next cell 

    End With 

Next Name 

這是一個很值得你的代碼只是,我刪除Select, Activate和參考,並聲明所有的變量。你也可以放棄循環,試試這樣內置的Range Methods

Dim r As Range, copy_r As Range, name, ws As Worksheet 

For Each name In Array("Sheet A", "Sheet B", _ 
         "Sheet C", "Sheet D") 
    Set ws = ThisWorkbook.Worksheets(name) 

    With ws 
     '/* set the range */ 
     Set r = .Range("A1", .Range("A" & .Rows.Count).End(xlUp)) 
     r.AutoFilter 1, "Total" '/* filter the range, all with "Total" */ 
     '/* set the range for copy, 10 cell based on your code? */ 
     Set copy_r = r.SpecialCells(xlCellTypeVisible).Offset(, 9) 
     '/* copy to the last empty row in column L */ 
     copy_r.Copy .Range("L" & .Range("L" & .Rows.Count).End(xlUp).Row + 1) 
     .AutoFilterMode = False '/* remove filtering */ 
    End With 

Next 
相關問題