简体   繁体   English

在Excel中使用数组时出现VBA运行时错误9

[英]VBA Runtime Error 9 while using Array in Excel

Below is a picture representing efficiency versus date of a given machine. 下图显示了效率与给定机器日期的关系。 Efficiencies aren't done daily but on random dates. 效率不是每天都做,而是随机安排。 This efficiency is then repeated till a new efficiency is added. 然后重复此效率,直到添加新的效率为止。 So in our case unique efficiencies are done on Day# 1,3,10 & 12. However you can see that efficiencies might repeat so the Day# 3 & 12 efficiency is same .. we can't use command Remove Dublicates 因此,在我们的案例中,第1、3、10和12天的效率是唯一的。但是,您可以看到效率可能会重复,因此第3、12天的效率是相同的.. 我们不能使用命令Remove Dublicates

在此处输入图片说明

The mission is to select those Dates where efficiency was entered on Day# 1,3,10 & 12, Using VBA I was somewhat able to do this, but it throws Error 9 at the end? 任务是选择在第1、3、10和12天输入效率的日期,使用VBA可以做到这一点,但是最后会引发错误9?

Sub AutoEffRemove()
Dim rangeToUse As Range, cell1 As Range, i As Integer, RowCount As Integer, MyArray() As Variant
Set rangeToUse = Selection
    For Each cell1 In Selection
        If cell1.Value = cell1.Offset(-1, 0).Value Then
        ReDim Preserve MyArray(RowCount)
        MyArray(RowCount) = cell1.Row
        RowCount = RowCount + 1
        End If
    Next cell1
    For i = 0 To WorksheetFunction.Count(MyArray)
    Rows(MyArray(i)).EntireRow.Delete
    'MsgBox MyArray(i)
    Next i
End Sub

MsgBox & Count(MyArray) do represent that code is targeting the required rows MsgBox和Count(MyArray)确实表示代码针对所需的行

The error is caused because your final For loop should either range from lbound(MyArray) to ubound(MyArray), or from 0 to WorksheetFunction.Count(MyArray)-1. 引起该错误的原因是,您最终的For循环的范围应从lbound(MyArray)到ubound(MyArray),或者从0到WorksheetFunction.Count(MyArray)-1。

Also, your final loop will not be deleting the rows you are expecting to remove. 同样,您的最终循环将不会删除您希望删除的行。 Once the first row is removed (row 4 in your example), all other cells will have shifted up one row, so the next deletion (of row 6) will actually remove what was originally row 7. 删除第一行(示例中的第4行)后,所有其他单元格都将上移一行,因此(第6行)的下一个删除实际上将删除最初的第7行。

So you will be better off performing your final loop from ubound(MyArray) to lbound(MyArray) step -1. 因此,最好执行从ubound(MyArray)到lbound(MyArray)步骤-1的最终循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM