[英]VBA: Subscript out of range error
I'm still pretty new with VBA, and keep getting the subscript out of range error. 我仍然是VBA的新手,并且继续使下标超出范围错误。 I am trying to write code that reads data from one excel tab ("ip") and writes some of that data to another tab ("rtf").
我正在尝试编写从一个excel选项卡(“ip”)读取数据的代码,并将一些数据写入另一个选项卡(“rtf”)。 When the ip tab has duplicate values for the variable ipIPCMP then I want to add a new row below the active row in my second tab rtf.
当ip选项卡有变量ipIPCMP的重复值时,我想在第二个选项卡rtf中的活动行下面添加一个新行。 The error occurs at the else part of the conditional statement.
该错误发生在条件语句的else部分。 Thank you.
谢谢。
UPDATE: changed else to elseif and changed the with statement. 更新:将else更改为elseif并更改了with语句。 Still get subscript out of range.
仍然有下标超出范围。
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
Next 下一个
Else:
to ElseIf
and add Then
to the end of the line. Else:
到ElseIf
并添加Then
到行尾。 Reference the range properly. 正确参考范围。
With Worksheets("rtf") .Range(.Cells(3 + i, 1), .Cells(3 + i, 8)).Activate ActiveCell.Offset(1).EntireRow.Insert End with
Note .Cells
and not Cells
. 注意
.Cells
而不是Cells
。 See this . 看到这个 。
Better Approach 更好的方法
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
The code sample you provided only tells half of the story but the above is the best I can offer without seeing the full story. 您提供的代码示例只讲述了故事的一半,但上面是我能提供的最好的,而没有看到完整的故事。
¹ See How to avoid using Select in Excel VBA macros for more methods on getting away from relying on select and activate to accomplish your goals. ¹ 请参阅如何避免在Excel VBA宏中使用选择以获取更多方法, 以避免依赖选择和激活来实现目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.