系統(tǒng):Windows 7
軟件:Excel 2016
- 本系列講講數(shù)組功能
- 今天說說如何清空數(shù)組的內(nèi)容
Part 1:實(shí)現(xiàn)內(nèi)容
- 有數(shù)組arr1,內(nèi)容為
Array(1, 2, 3, 4)
,增加一個(gè)元素成為arr2,如下圖 - 有數(shù)組arr3,內(nèi)容為
[{1,3,5,7,9}]
,清空成為arr4
arr1
1.png
arr2
2.png
arr3
3.png
arr4
4.png
Part 2: 代碼
Sub main()
Dim arr1()
arr1 = Array(1, 2, 3, 4)
ele = 5
temp = arr1
arr2 = arrAppend(temp, ele)
arr3 = [{1,3,5,7,9}]
temp = arr3
arr4 = arrClear(temp)
UCount = UBound(arr4)
LCount = LBound(arr4)
If IsEmpty(arr4(0)) Then
Debug.Print ("空")
End If
End Sub
Function arrAppend(arr, ele)
UCount1 = UBound(arr)
LCount1 = LBound(arr)
' 增加元素
' 先擴(kuò)大數(shù)組范圍,再賦值新元素
ReDim Preserve arr(LCount1 To UCount1 + 1)
arr(UCount1 + 1) = ele
arrAppend = arr
End Function
Function arrClear(arr)
ReDim arr(0)
arrClear = arr
End Function
代碼截圖
5.png
運(yùn)行過程數(shù)據(jù)
6.png
Part 3: 部分代碼解讀
-
temp = arr1
在傳入函數(shù)前對(duì)使用temp
變量進(jìn)行賦值,因?yàn)楹瘮?shù)內(nèi)部對(duì)變量的更改會(huì)隨著函數(shù)運(yùn)行結(jié)束而返回到調(diào)用該函數(shù)的過程,也就是會(huì)改變其初始值,這不是我想要的,所以使用一個(gè)臨時(shí)變量,關(guān)于該方面可見之前寫過的文章 - 在數(shù)組末尾增加元素和上一節(jié)方法相同,只是封裝在一個(gè)函數(shù)中
-
ReDim arr(0)
清空元素,采用Redim重新定義即可,與上一文的區(qū)別是:無Preserve。注意采用這種方式,含有的唯一元素取值為空。如果此時(shí)向其增加元素,會(huì)在空值元素后面增加,而不是頂替空元素
增加元素
7.png
對(duì)應(yīng)代碼
Sub main()
Dim arr1()
arr1 = Array(1, 2, 3, 4)
ele = 5
temp = arr1
arr2 = arrAppend(temp, ele)
arr3 = [{1,3,5,7,9}]
temp = arr3
arr4 = arrClear(temp)
UCount = UBound(arr4)
LCount = LBound(arr4)
If IsEmpty(arr4(0)) Then
Debug.Print ("空")
End If
ele = 5
temp = arr4
arr5 = arrAppend(temp, ele)
End Sub
- 更多學(xué)習(xí)交流,可加小編微信號(hào)
learningBin
更多精彩,請(qǐng)關(guān)注微信公眾號(hào)
掃描二維碼,關(guān)注本公眾號(hào)
公眾號(hào)底部二維碼.jpg