|
本帖最后由 loquat 于 2022-4-17 13:54 编辑
ReDim Preserve 二维数组是不可以的,偶然玩一下,写了这么个函数
- Public Sub ReDimPreserve(arrPreserve, ByVal end_row2&, ByVal end_col2&, Optional ByVal start_row2, Optional ByVal start_col2)
- '功能:突破ReDim Preserve不能处理二维数组的限制
- '参数1:arrPreserve待重置的数组
- '参数2:end_row2
- '参数3:end_col2
- '参数4:start_row2,可选,默认为原始数组第1维下标
- '参数5:start_col2,可选,默认为原始数组第2维下标
- '注意:1、未对上下标参数的大小做判断,请自行注意
- Dim arrTemp As Variant
- Dim i As Long, j As Long
- Dim start_row1 As Long, end_row1 As Long
- Dim start_col1 As Long, end_col1 As Long
- If Not IsArray(arrPreserve) Then Exit Sub
- start_row1 = LBound(arrPreserve, 1)
- end_row1 = UBound(arrPreserve, 1)
- start_col1 = LBound(arrPreserve, 2)
- end_col1 = UBound(arrPreserve, 2)
- If VarType(start_row2) = 10 Then start_row2 = start_row1 '设置默认下标,vbError = 10
- If VarType(start_col2) = 10 Then start_col2 = start_col1 '设置默认下标
- ReDim arrTemp(start_row2 To end_row2, start_col2 To end_col2)
- If start_row2 > end_row1 Or _
- end_row2 < start_row1 Or _
- start_col2 > end_col1 Or _
- end_col2 < start_col1 Then '容错判断,新数组完全不在原始数组上下标范围内
- Err.Raise 0, "ReDimPreserve", "上标或下标超出原始范围"
- Exit Sub
- Else '至少包含了原始数组的一部分
- If start_row2 > start_row1 Then start_row1 = start_row2
- If start_col2 > start_col1 Then start_col1 = start_col2
- If end_row2 < end_row1 Then end_row1 = end_row2
- If end_col2 < end_col1 Then end_col1 = end_col2
- For i = start_row1 To end_row1 '以修正后的原始数组上下标范围复制数据
- For j = start_col1 To end_col1
- arrTemp(i, j) = arrPreserve(i, j) '复制数据
- Next
- Next
- arrPreserve = arrTemp '传址方式返回
- End If
- End Sub
复制代码
不同于ReDim Preserve语句,这个函数会对上下标做截断处理,而不是像前者那样,直接改变上下标本身。
使用示例:
- Sub Test()
- Dim arr
- ReDim arr(1 To 4, 1 To 4)
- Dim i&, j&
- For i = 1 To 4
- For j = 1 To 4
- arr(i, j) = i & "-" & j
- Next j
- Next i
- ReDimPreserve arr, 3, 3, 0, 0
- ReDimPreserve arr, 3, 3, 2, 2
- End Sub
复制代码 |
评分
-
1
查看全部评分
-
|