arrays - 下标超出范围
问题描述
我的代码有问题。我正在尝试将数据从一个工作表发布到另一个工作表。我在代码中定义了两个工作表,并将工作表范围放在一个数组中。然后我想创建一个循环,如果 D 列的数字为 3 或更高,则该循环将从我的业务表中的业务表中的 E 列中发布数据。但是,当我运行它时,它说
Subscript is out if range
我的代码如下
Sub Simple_if2()
Dim shB As Worksheet, shE As Worksheet, lastRB As Long, lastRE As Long
Dim score As Integer, i As Long, k As Long, arrB As Variant
'Worksheet definitions
Set shB = Worksheets("Business")
Set shE = Worksheets("Engagement Plan (High Priority)")
lastRB = shB.Range("D" & shB.Rows.Count).End(xlUp).Row
lastRE = shB.Range("E" & shB.Rows.Count).End(xlUp).Row
arrB = shB.Range("D6:E6" & lastRB & lastRE).Value 'put the shB sheet range in an array
ReDim arrE(UBound(arrB)) 'redim arrE at maximum possible dimension
'Loop for Business worksheet
For i = 1 To UBound(arrB)
If arrB(2, i) >= 3 Then
arrE(k) = arrB(1, i) 'fill arrE only with elements >=3
k = k + 1
End If
Next i
ReDim Preserve arrE(k + 1) 'redim the array to keep only the filled elements
'drop the array content at once:
shE.Range("B3").Resize(UBound(arrE) + 1, 1).Value = WorksheetFunction.Transpose(arrE)
End Sub
解决方案
- 交换
2
andi
和3
andi
:arrB(i, 1)
andarrB(i, 2)
- 在将范围读
.Value
入数组之前更正范围的引用:shB.Range("D6:E" & lastRE).Value
Dim shB As Worksheet, shE As Worksheet, lastRB As Long, lastRE As Long
Dim score As Integer, i As Long, k As Long, arrB As Variant
'Worksheet definitions
Set shB = Worksheets("Business")
Set shE = Worksheets("Engagement Plan (High Priority)")
lastRB = shB.Range("D" & shB.Rows.Count).End(xlUp).Row
lastRE = shB.Range("E" & shB.Rows.Count).End(xlUp).Row
arrB = shB.Range("D6:E" & lastRE).Value 'put the shB sheet range in an array
ReDim arrE(UBound(arrB)) 'redim arrE at maximum possible dimension
'Loop for Business worksheet
For i = 1 To UBound(arrB)
If arrB(i, 1) >= 3 Then
arrE(k) = arrB(i, 2) 'fill arrE only with elements >=3
k = k + 1
End If
Next i
ReDim Preserve arrE(k + 1) 'redim the array to keep only the filled elements
'drop the array content at once:
shE.Range("B3").Resize(UBound(arrE) + 1, 1).Value = WorksheetFunction.Transpose(arrE)
End Sub
推荐阅读
- python - 如何在 discord.py 中添加条件冷却?
- augmented-reality - 此应用程序需要在虚幻游戏中使用最新版本的arcore
- python - 尽管定义了变量,但出现名称未定义错误
- mysql - MySQL 中的递归查询(找到 Bob 的直接和间接主管)?
- html - SVG 动画圆圈垂直和水平居中
- python - 为什么使用 `as_index=False` 的 `groupby` 甚至比使用 `reset_index` 的 `groupby` 还要慢
- f# - 在 F# Akka.Net 中区分远程参与者之间的联合
- android - 如何使用NFC标签直接打开APP安卓
- scala - 有没有更好的方法来测试 Scala 中的泛型类型(没有类型参数)?
- docker - 在视频下载器中使用 ffmpeg 时出错:'ERR: spawn ./db/ffmpeg ENOENT'