【发布时间】:2021-01-23 08:31:28
【问题描述】:
我正在尝试从该行中已更改的单元格中选择一行,然后从选定的行值中填充一个数组。
当我尝试构建一个包含所选行(如 Copyrange = Start Position & End Position)的字符串变量,然后将其提供给 Range 参数到数组中时,它会引发下标超出范围错误。
我需要制定正确的行来分配给 Range,如果不能将字符串变量传递给 Range 参数,我该怎么办?
Private Sub Worksheet_Change(ByVal Target As Range)
Dim r, s As Long
If Not Application.Intersect(Target, Range("PrioritySelect")) Is Nothing Then
If Not Application.Intersect(Target, Range("PrioritySelect")) = "Select" Then
r = Target.Row
s = r + 8
' MsgBox "row " & r, , "Amended Cell..."
Dim MyArray() As Variant
'unallocated array
Dim i As Integer
Dim ThisWs As Worksheet
Dim Copyrange As String
Dim Position As String
Set ThisWs = Worksheets("PIPPR")
Position = "B" & r
EndPosition = "B" & s
MsgBox Position
MsgBox EndPosition
Let Copyrange = Position & ":" & EndPosition
MsgBox Copyrange
MyArray = ThisWs.Range(Copyrange).Value2
MsgBox "Lower Bound = " & LBound(MyArray)
MsgBox "Upper Bound = " & UBound(MyArray)
MsgBox MyArray(1)
'MsgBox MyArray(1)
' Print student marks from the array to the Immediate Window
Debug.Print "Values"
For i = LBound(MyArray) To UBound(MyArray)
Debug.Print MyArray(i)
Next i
【问题讨论】:
-
尝试使用
Copyrange = Position & ":" & EndPosition而不是Let Copyrange = Position & ":" & EndPosition。字符串必须以这种简单的方式接收值。 -
ThisWs.Range(Copyrange)cannot give a subscript out of range 错误。你得到它的地方是MyArray(1)。MyArray是二维数组,不是一维数组。
标签: arrays excel vba string range