简体   繁体   English

VBA 循环遍历数组但运行时错误 9 下标超出范围

[英]VBA Looping through an array but getting runtime error 9 subscript out of range

I have some experience with C/PHP but am not that fluent in VBA.我有一些使用 C/PHP 的经验,但对 VBA 不太熟悉。 I have a list of 30 items in excel, each with particular specs and I am just going down the list, comparing each item's specs pairwise against those below it.我在 excel 中有一个包含 30 个项目的列表,每个项目都有特定的规格,我只是在列表中列出,将每个项目的规格与下面的成对比较。 If there's a match, I put a 1 in the column next to the item.如果有匹配项,我会在项目旁边的列中输入 1。 But I'm getting a runtime error 9 subscript out of range (I don't think I'm exceeding line 30 or column 5 at any point).但是我得到一个运行时错误 9 下标超出范围(我认为我在任何时候都没有超过第 30 行或第 5 列)。 It occurs at the line where I check if the conditions are fulfilled:它发生在我检查条件是否满足的那一行:

If data(rowi, 1) = data(rowj, 1) And data(rowi, 2) = data(rowj, 2) And Abs(data(rowi, 5) = data(rowj, 5)) = 2 Then

Sub test()
    Dim data As Variant
    Dim rowi As Integer
    Dim rowj As Integer
    
    data = Range("B2:F31").Value
        For rowi = 0 To 28
        For rowj = rowi + 1 To 29
            If data(rowi, 1) = data(rowj, 1) And data(rowi, 2) = data(rowj, 2) And Abs(data(rowi, 5) = data(rowj, 5)) = 2 Then
                    Cells(rowi, 11).Value = 1
            End If
        Next rowj
    Next rowi
End Sub

Find Matches Below在下面查找匹配项

Option Explicit

Sub test()
    
    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    Dim rg As Range: Set rg = ws.Range("B2:F31")
    Dim rCount As Long: rCount = rg.Rows.Count
    Dim rOffset As Long: rOffset = rg.Row - 1
    
    Dim Data() As Variant: Data = rg.Value
    
    Dim ri As Long
    Dim rj As Long
    
    For ri = 1 To rCount - 1
        For rj = ri + 1 To rCount
            If Data(ri, 1) = Data(rj, 1) _
                    And Data(ri, 2) = Data(rj, 2) _
                    And Abs(Data(ri, 5) - Data(rj, 5)) = 2 Then
                ws.Cells(ri + rOffset, 11).Value = 1
                Exit For
            End If
        Next rj
    Next ri

End Sub

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

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