如何解决对象所需的错误

时间:2015-09-30 21:12:36

标签: vba excel-vba excel

我正在处理一个宏,它可以帮助我在条件下将数据从一个工作表复制到另一个工作表。我尝试了以下代码,但我得到了一个对象需要错误

感谢任何帮助

Sub copier()
   Dim ws1 As Worksheet, ws2 As Worksheet, src As Range, dest As Range, i As Integer

   Set ws1 = Worksheets("Workload - Charge de travail")
   Set ws2 = Worksheets("Sheet1")

   For i = 2 To ws1.Range("A1").SpecialCells(xlLastCell).Row        

       Set src = ws1.Range("A" & i & ":AL" & i + 50)
       Set dest = ws2.Range("A" & i & ":AL" & i + 50)

        If Source.Cells(i, 31).Value = "Completed - Appointment made / Complété - Nomination faite" Then

          '(i,31) this is  for my drop down list's condition


          src.Copy Destination:=dest
          dest.Value = dest.Value
       End If
   Next i
End Sub

3 个答案:

答案 0 :(得分:1)

Salut,veuyer verifier que" Source",不应该是表格" src"。

我也猜测你一次只想复制一行,

  • Range("A" & i & ":AL" & i) which is "A2:AL2" rather than
  • Range("A" & i & ":AL" & i + 50) is "A2:AL52"

同时检查单元格(y,31)是否为" AE",它位于AL之前(第38列)。

答案 1 :(得分:0)

您使用Source代替src

 If Source.Cells(i, 31).Value = "Completed - Appointment made / Complété...

答案 2 :(得分:0)

有一些问题,Source不应该src它应该是ws1。在行src已经引用之后,src.cells(i ...)将转到i行。如果我是50那么它将从第100行得到结果。

另外我相信你只需要一次复制一行而不是50行。

 Sub copier()
    Dim ws1 As Worksheet, ws2 As Worksheet, src As Range, dest As Range, i As Integer

    Set ws1 = Worksheets("Workload - Charge de travail")
    Set ws2 = Worksheets("Sheet1")

    For i = 2 To ws1.Range("A1").SpecialCells(xlLastCell).Row

        Set src = ws1.Range("A" & i & ":AL" & i)
        Set dest = ws2.Range("A" & i & ":AL" & i)

         If ws1.Cells(i, 31).value = "Completed - Appointment made / Complété - Nomination faite" Then

           '(i,31) this is  for my drop down list's condition


           src.Copy Destination:=dest
           'dest.value = dest.value
        End If
    Next i
End Sub