2017-07-31 46 views
1

我在VBA中有點新。我想要做的是在一行(n)中找到單詞「材料」,從上面複製它的所有單元格,並將它們粘貼到列A中的另一個表單中。arr2 - 列將使用相同的功能但具有不同的話。 從我的代碼,我不斷收到錯誤。你能幫我解決代碼嗎?查找「材質」,複製它的單元格並粘貼到另一個工作表中

Dim t As Range 
    n = InputBox("Row number of FIRST MATERIAL") 
    arr2 = Array("A", "D", "E", "O", "P", "S", "W", "Y", "AB") 
    Set t = Sheets("Project Parts Requisitioning").Rows(n).Find("*Material*", LookAt:=xlWhole) 
     If t Is Nothing Then 
     MsgBox ("Material was not found") 
     End If 

     If Not t Is Nothing Then 
     Sheets("Project Parts Requisitioning").Rows(n).Find("*Material*", LookAt:=xlWhole).End(xlDown).Copy 
     Sheets("GCC1").Column("A").PasteSpecial xlPasteValues 

     End If 
+2

什麼線你得到的錯誤?什麼是錯誤? – Zac

+1

爲什麼你創建一個數組而不是在代碼中引用它? – Luuklag

回答

1

的問題如下:

這一行:

Sheets("Project Parts Requisitioning").Rows(n).Find("*Material*", _ 
LookAt:=xlWhole).End(xlDown).Copy 

您複製的最後一個單元在給定的表。例如。行1048576或更低的單元格,從找到的一個。但是你只複製一個單元格。 然後用下一行

Sheets("GCC1").Column("A").PasteSpecial xlPasteValues 

您嘗試將此單元格粘貼到列中。這不會發生。


一般來說,嘗試將代碼重寫成某個東西,任何人都可以輕鬆地重現。那麼錯誤會更明顯。就像這樣:

Option Explicit 
Public Sub TestMe() 

    Dim n    As Long 
    Dim t    As Range 
    Dim arr2   As Variant 
    Dim strToLookFor As String: strToLookFor = "*Material*" 

    n = 11 'you do not need an input box for testing purposes 

    'How do you use this array? 
    arr2 = Array("A", "D", "E", "O", "P", "S", "W", "Y", "AB") 

    Set t = Worksheets(1).Rows(n).Find(strToLookFor, LookAt:=xlWhole) 

    If t Is Nothing Then 
     Debug.Print ("Material was not found") 'No msgbox when testing 
    End If 

    If Not t Is Nothing Then 
     'you copy only one cell here 
     Worksheets(3).Rows(n).Find(strToLookFor, LookAt:=xlWhole).End(xlDown).Copy 

     'but you try to paste it in a column? 
     Worksheets(4).Column("A").PasteSpecial xlPasteValues 
    End If 

End Sub 
1

試試這個

Sub testso1() 

Dim t As Range 
    n = InputBox("Row number of FIRST MATERIAL") 
    arr2 = Array("A", "D", "E", "O", "P", "S", "W", "Y", "AB") 
    Set t = Sheets("Project Parts Requisitioning").Rows(n).Find("*Material*", LookAt:=xlWhole) 

    If Not t Is Nothing Then 
     Sheets("GCC1").Columns("A") = t.EntireColumn.Value 
    Else 
     MsgBox ("Material was not found") 
    End If 

End Sub 
相關問題