接收运行时错误' 9'

时间:2018-03-26 18:57:46

标签: excel vba excel-vba

我刚刚开始学习一个月前如何使用Python编程,我也想了解一下VBA。我有一张包含3张纸的excel文档,第一张是包含A到W列和几千行的库存。第二张是有问题的资产,第三张是结果的目的地。

这是宏的伪代码:

  • 激活第二张表格
  • 创建循环以浏览A列的内容并突出显示每个
  • 逐行将每行的内容复制到变量
  • 激活第一张图片
  • 循环列C和D的内容,用于上述变量
  • 如果找到则突出显示活动行
  • 将活动行复制到从A
  • 开始的下一个可用行中的第3页

我研究了过去几天如何解决这个问题,找到搜索代码,循环遍历行,选择合适的行,在表单之间进行复制命令。有了这些,我写了我认为应该用于预期目的的东西。我已经为每一行添加了评论,以便我的思考过程。

我目前收到的错误:运行时错误' 9':下标超出范围 错误位置:第12行 - 我将目标表设置为Sheet(0)。

非常感谢您的帮助!

Sub SpecialCopy()
  Dim targetSh, destinationSh, invSh As Worksheet
  Set targetSh = Sheets(1)  'Setting initial value to Page 2 which contains assets being searched for
  Set destinationSh = Sheets(2)   'Using a second one for use in the final copy statement to the destination sheet
  Dim i As Long
  Dim g As Long
  Dim asset As String 'Using string as asset row may contain all numbers or numbers and letters

  For g = 1 To Cells(Rows.Count, "A").End(xlUp).row 'Using loop to loop through values in column containing assets being searched for
    Set targetSh = Sheets(1)
    asset = Cells(g, 1).Value  'Setting asset to next value in Sheet 2
    Set targetSh = Sheets(0) 'Not sure if I should initialize a third worksheet to use as the worksheet containing inventory, or if setting it twice in the loop would work.
    For i = 1 To Cells(Rows.Count, "F").End(xlUp).row  'Looping through values in inventory to find asset
      If Cells(i, 3).Value = asset Then
        Range(Cells(i, 1), Cells(i, 23)).Copy Destination:=destinationSh.Range("A" & targetSh.Cells(Rows.Count, "A").End(xlUp).row + 1)  'Trying to copy the found asset, including all rows from A to W from Sheet(0) to Sheet(2)
      End If
    Next i
  Next g
End Sub

代码可以在Github上找到:https://github.com/cookchelsea/Find_and_Paste/blob/master/Master

1 个答案:

答案 0 :(得分:1)

工作表的起点是Sheet(1),因此指向Sheet(0)会得到运行时错误9,在这种情况下是因为你引用了一个不存在的集合(没有Sheet( 0))。有关该错误代码的更多信息here