【发布时间】:2021-05-02 11:02:59
【问题描述】:
我的代码有问题。我正在尝试将数据从一个工作表发布到另一个工作表。我在代码中定义了两个工作表,并将工作表范围放在一个数组中。然后,我想创建一个循环,如果 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
【问题讨论】:
-
注意:
shB.Range("D6:E6" & lastRB & lastRE)可能是错误的范围...Debug.Print "D6:E6" & lastRB & lastRE看看结果是什么。 -
我认为你的 refs 应该是
arrB(i, 2)和arrB(i, 1) -
@BigBen - 它给了我一个错误,说类型不匹配。如何用“Debug.Print”定义我的“arrB”?
-
不,只是
Debug.Print "D6:E6" & lastRB & lastRE。结果将类似于即时窗口中的D6:E65555。 -
@BigBen 成功了!
arrB=shB.Range("D6:E" & lastRB).value工作。谢谢大佬