【问题标题】:Subscript is out of range下标超出范围
【发布时间】: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 工作。谢谢大佬

标签: arrays excel vba range


【解决方案1】:
  1. 交换2i3iarrB(i, 1)arrB(i, 2)
  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

【讨论】:

    猜你喜欢
    • 2015-05-27
    • 2021-09-18
    • 2012-04-28
    • 2017-01-18
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多