问题描述
dim arr(1 to 5) as string
arr(1)="a"
arr(3)="b"
arr(5) = "c"
(arr(2),arr(4) 为空).
我如何重新定义这个 arr(1to5) 以排除空值并保存值“a”、“b”、“c”(我想要像 arr(1to3),arr(1)="a",arr(2)="b",arr(3)="c"
这样的输出)?
一般来说,我不知道其中有多少是空的,所以我需要一些通用代码(不是针对这个特定示例)。
我正在考虑使用新的临时数组来保存所有非空值,然后重新映射 arr(1to5)。
I wrote sth similar:
Sub test()
Dim myArray() As String
Dim i As Long
Dim y As Long
ReDim Preserve myArray(3)
myArray(1) = "a"
myArray(3) = "c"
Dim myArray2() As String
y = 1
For i = LBound(myArray) To UBound(myArray)
If myArray(i) <> "" Then
ReDim Preserve myArray2(y)
myArray2(y) = myArray(i)
y = y + 1
End If
Next i
ReDim myArray(UBound(myArray2))
myArray = myArray2
End Sub
但是我想避免创建新数组。
解决方法
创建一个相同大小的新数组。循环第一个数组并将非空时的值插入新数组中,跟踪新数组中具有值的最后一个位置,然后将新数组重新调整为仅具有值的大小。
Sub kjlkj()
Dim arr(1 To 5) As String
arr(1) = "a"
arr(3) = "b"
arr(5) = "c"
Dim newArr() As String
ReDim newArr(1 To UBound(arr))
Dim j As Long
j = LBound(newArr)
Dim i As Long
For i = LBound(arr) To UBound(arr)
If arr(i) <> "" Then
newArr(j) = arr(i)
j = j + 1
End If
Next i
ReDim Preserve newArr(LBound(newArr) To j - 1)
'do what you want with the new array.
End Sub
,
通过 Filter()
函数替代
“但是我想避免创建新数组。”
否定过滤允许一个基本简单的替代方案,但是你必须
- 动态声明您的数组(即没有预设数量的元素)以允许重建覆盖原始数组,
- 对连接的数组元素执行双重替换,以允许插入可以过滤掉的唯一字符。
Sub testFilter()
Dim arr() As String
ReDim arr(1 To 5)
arr(1) = "a"
arr(3) = "b"
arr(5) = "c"
'Debug.Print Join(arr,",") ' ~~> a,b,c
'rearrange arr via RemoveEmpty()
arr = RemoveEmpty(arr) ' >> function RemoveEmpty()
Debug.Print Join(arr,") ' ~~> a,c
End Sub
帮助函数 RemoveEmpty()
添加未使用的唯一字符,例如$
,对空元素加上最终的否定过滤允许删除这些标记的元素。
注意双替换是必要的,以允许用 $
标记标记连续的空元素,因为 VBA 会在这里跳过额外的字符。 >
Function RemoveEmpty(arr)
Dim tmp
tmp = Replace(Replace(Join(arr,"|"),"||","|$|"),"|$|")
RemoveEmpty = Filter(Split(tmp,"$",False)
End Function