2017-07-31 268 views
0

我有一個宏在列中搜索特定值,如果爲true,則將包含該值的所有行復制到不同的工作表。但是,它似乎不工作,因爲它只複製最後一行,而不是具有特定值的所有行。複製粘貼宏

基本上,我向B列輸入數據,列C通過VLOOKUP返回結果,列D列出TRUE/FALSE。當D列中的值返回TRUE時,我希望它複製整行並將其粘貼到另一個工作表中。

Private Sub CommandButton21_Click() 
    Dim LR As Long 
    Dim C As Range 
    Dim Test As Worksheet 
    Dim Pastesheet As Worksheet 

    'Find the last row with data in column C 
    LR = ActiveSheet.Cells(Rows.Count, "C").End(xlUp).Row 

    'look at every cell in D2 onwards 
    For Each C In Range("D2:D" & LR) 
     If C.Value = True Then 

      'Copy code 
      Set Test = Worksheets("Test Sheet") ' Copy From this sheet 
      Set Pastesheet = Worksheets("Inventory") ' to this sheet 

      C.EntireRow.Copy ' copy the row from column D that meets that requirements 
      Pastesheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValuesAndNumberFormats   
     End If  
    Next C 
End Sub 
+0

很可能想要改變'LR = ActiveSheet.Cells()'來讓你計算單元格的實際表單。此外,添加您想要「C」範圍的工作表。現在,只有'Range(「D2:D」&LR)'它將使用ActiveSheet。 – BruceWayne

+0

只需在循環前獲得PasteSheet中的最後一行,然後定義一個計數器並在循環中添加counter = counter + 1並將計數器用作粘貼整行的行。關於這一點的好處是,你還將計算你有多少比賽 – Ibo

+0

謝謝你們,有什麼機會,你可以準確地輸入這些建議的位置?編寫宏我很新。這將不勝感激。 – zshake

回答

0

我猜你在A列中沒有任何東西。使用其他方法找到最後一行。當你的循環開始時加緊你的範圍。

這應該工作:

Private Sub CommandButton21_Click() 
    Dim LR As Long 
    Dim C As Range 
    Dim Test As Worksheet 
    Dim Pastesheet As Worksheet 
    Dim LastRowOnSheet As Long 

    'Find the last row with data in column C 
    LR = ActiveSheet.Cells(Rows.Count, "C").End(xlUp).Row 

    'look at every cell in D2 onwards 

     Set Test = Worksheets("Test Sheet") ' Copy From this sheet 
     Set Pastesheet = Worksheets("Inventory") ' to this sheet 

    For Each C In Test.Range("D2:D" & LR).Cells 


    If C.Value = True Then '(you can actually type "if c.value then" but no difference) 

     'Copy code    

     LastRowOnSheet = Pastesheet.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row 

     C.EntireRow.Copy 'copy the row from column D that meets that requirements 

     Pastesheet.Cells(LastRowOnSheet + 1, 1).PasteSpecial xlPasteValuesAndNumberFormats 

    End If 

    Next C 

    End Sub 

@zshake該錯誤表明沒有定義的片材或片整體爲空白。 find命令沒有錯誤。測試以確保pasteSheet有效。你可以把這個在1行代碼上面的你在哪裏得到的錯誤做到這一點:

msgbox Pastesheet.name

如果顯示的工作表名稱,你是在紙張上良好。然後你可以測試一個地址:

Dim Wth as range 
Set Wth = Pastesheet.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious) 
if wth is nothing then 
msgbox "Cannot find a cell" 
else 
msgbox "found a cell at " & wth.address 
EndIf 
+0

我在LastRowOnSheet = Pastesheet.Cells.Find(「*」,searchorder:= xlByRows,searchdirection:= xlPrevious).Row。錯誤說:「對象變量或變量塊未設置」 – zshake

+0

列A空白,但我的命令按鈕存在 – zshake

+0

列C或D是否爲空白? – Robby