VBA:下标超出范围错误

时间:2015-12-29 16:51:39

标签: excel vba excel-vba

我仍然是VBA的新手,并且继续使下标超出范围错误。我正在尝试编写从一个excel选项卡(“ip”)读取数据的代码,并将一些数据写入另一个选项卡(“rtf”)。当ip选项卡有变量ipIPCMP的重复值时,我想在第二个选项卡rtf中的活动行下面添加一个新行。该错误发生在条件语句的else部分。谢谢。

更新:将else更改为elseif并更改了with语句。仍然有下标超出范围。

For i = 1 To n   

connectIPCMP = iPCMP(i)

    For j = 1 To m

    ipIPCMP = Sheets("ip").Cells(j + 1, 2)

        If ipIPCMP = connectIPCMP And k = 1 Then

            supplierList = Sheets("ip").Cells(j, 3)

            Sheets("rft").Cells(3 + j, 4) = list
            k = k + 1

         ElseIf ipointIPCMP = connectIPCMP And k > 1 Then

             With Worksheets("rtf")

                .Range(.Cells(3 + i, 1), .Cells(3 + i, 8)).Activate
                .ActiveCell.Offset(1).EntireRow.Insert

             End With

            Sheets("rft").Cells(3 + j, 4) = supplierList

            k = k + 1

        End If
    Next

下一步

1 个答案:

答案 0 :(得分:3)

  1. Else:更改为ElseIf并将Then添加到该行的末尾。
  2. 正确参考范围。

    With Worksheets("rtf")
         .Range(.Cells(3 + i, 1), .Cells(3 + i, 8)).Activate
         ActiveCell.Offset(1).EntireRow.Insert
    End with
    
  3. 注意.Cells而非Cells。请参阅this

    更好的方法

        For i = 1 To n
            connectIPCMP = iPCMP(i)
            With Worksheets("rtf")   '<~~CHECK THIS WORKSHEET NAME!!!!!
                For j = 1 To m
                    ipIPCMP = Worksheets("ip").Cells(j + 1, 2)
                    If ipIPCMP = connectIPCMP And k = 1 Then
                        supplierList = Sheets("ip").Cells(j, 3)
                        .Cells(3 + j, 4) = List
                        k = k + 1
                    ElseIf ipointIPCMP = connectIPCMP And k > 1 Then
                        .Cells(3 + i, 1).Offset(1).EntireRow.Insert  '<~~only need a single cell if you are going to insert an entire row
                        .Cells(3 + j, 4) = supplierList
                        k = k + 1
                    End If
                Next j
            End With
        Next i
    

    您提供的代码示例只讲述了故事的一半,但上面是我能提供的最佳内容而没有看到完整的故事。

    ¹有关远离依赖选择和激活以实现目标的更多方法,请参阅How to avoid using Select in Excel VBA macros