所谓的加强版是因为以前已经写过可以改LBound的ReDim了
所谓的再强化版是因为这次的这个可以修改任何类型的动态数组,是不是很邪恶
唯一的遗憾是必须是动态数组,还有只适用于1维,多维的代码太麻烦了

Option Explicit
Private Declare Sub CopyMemory Lib "KERNEL32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Declare Sub ZeroMemory Lib "KERNEL32" Alias "RtlZeroMemory" (dest As Any, ByVal numBytes As Long)
Private Declare Function VarPtrArray Lib "msvbvm60.dll" Alias "VarPtr" (Var() As Any) As Long
Private Type SafeArray
cDims As Integer '这个数组有几维?
fFeature As Integer '这个数组有什么特性?
cbElements As Long '数组的每个元素有多大?
cLocks As Long '这个数组被锁定过几次?
pvData As Long '这个数组里的数据放在什么地方?
End Type
Private Type Var
VarType As Integer
UnknownA As Integer
UnknownB As Long
Ptr As Long
UnknownC As Long
End Type
Function ReDim_Preserve(Arr As Variant, NewLBound As Long, NewUBound As Long) As Boolean
Dim Bits() As Byte '缓冲
Dim CopySize As Long '复制长度
Dim CopyPoint As Long '复制点
'数组结构
Dim ArrStruct As SafeArray
Dim BitsStruct As SafeArray
'数组指针
Dim VarStruct As Var
Dim ArrPoint As Long
Dim BitsPoint As Long
'复制范围
Dim CopyLBound As Long
Dim CopyUBound As Long
'交换指针
Dim SwapPoint As Long
On Error GoTo Err
If IsArray(Arr) And NewUBound >= NewLBound Then '判断是否有意义
Call CopyMemory(VarStruct, Arr, 16)
Call CopyMemory(ArrPoint, ByVal VarStruct.Ptr, 4) '得到头指针
Call CopyMemory(ArrStruct, ByVal ArrPoint, LenB(ArrStruct)) '得到数组结构
If ArrStruct.cDims = 0 Then '判断是否为空
ReDim Arr(NewLBound To NewUBound)
Else
'得到复制范围
If NewLBound > LBound(Arr) Then CopyLBound = NewLBound Else CopyLBound = LBound(Arr)
If NewUBound < UBound(Arr) Then CopyUBound = NewUBound Else CopyUBound = UBound(Arr)
CopySize = (CopyUBound - CopyLBound + 1) * ArrStruct.cbElements
ReDim Bits(1 To CopySize) '申请内存
CopyPoint = ArrStruct.pvData + (CopyLBound - LBound(Arr)) * ArrStruct.cbElements
Call CopyMemory(Bits(1), ByVal CopyPoint, CopySize) '复制
Call ZeroMemory(ByVal CopyPoint, CopySize) '保险起见,清除原先的信息
ReDim Arr(NewLBound To NewUBound) '改变大小
'得到新数组信息
Call CopyMemory(VarStruct, Arr, 16)
Call CopyMemory(ArrPoint, ByVal VarStruct.Ptr, 4) '得到头指针
Call CopyMemory(ArrStruct, ByVal ArrPoint, LenB(ArrStruct)) '得到数组结构
'得到缓冲信息
Call CopyMemory(BitsPoint, ByVal VarPtrArray(Bits), 4)
Call CopyMemory(BitsStruct, ByVal BitsPoint, LenB(BitsStruct)) '得到数组结构
'交换指针
SwapPoint = ArrStruct.pvData
ArrStruct.pvData = BitsStruct.pvData
BitsStruct.pvData = SwapPoint
Call CopyMemory(ByVal ArrPoint, ArrStruct, LenB(ArrStruct)) '得到数组结构
Call CopyMemory(ByVal BitsPoint, BitsStruct, LenB(BitsStruct)) '得到数组结构
ReDim_Preserve = True '成功
End If
End If
Err:
End Function
'测试代码
Private Sub Command1_Click()
ReDim a(5) As String
Dim i As Long
For i = 1 To 5
a(i) = i
Next
Call ReDim_Preserve(a, 2, 4)
End Sub