![](/img/trans.png)
[英]excel VBA (not VBScript) 101: How do I create and read a multidimensional array?
[英]How do I create a VBScript multiline array?
我有一個VBScript文件,我使用它在數組中有很多值。
recipes = Array("chicken soup","turkey","mash potatoes","yams","stuffing")
在多行上聲明此數組的正確方法是什么,類似於:
recipes = Array("chicken soup",
"turkey",
"mash potatoes",
"yams",
"stuffing")
這樣我就可以在每一行寫評論(或者這是正確的嗎?):
recipes = Array("chicken soup", 'broth, noodles, chicken
"turkey", 'YUMMY i love turkey
"mash potatoes", 'butter, sour cream, cook 20mins
"yams", 'dont forget the marshmallows
"stuffing") 'celery, jiffy cornbread, broth
如果要逐行聲明數組值以允許注釋,則有兩個選項。
如果您有固定數量的數組項,則可以定義該數組,然后填充每個元素。
Dim receipes(4) Dim receipe receipes(0) = "chicken soup" 'Chicken Soup receipes(1) = "turkey" 'Turkey receipes(2) = "mash potatoes" 'Mash Potatoes receipes(3) = "yams" 'Yams receipes(4) = "stuffing" 'Stuffing For Each receipe In receipes WScript.Echo receipe Next
輸出:
chicken soup turkey mash potatoes yams stuffing
如果需要動態聲明,可以使用ReDim
。 Preserve
關鍵字告訴ReDim
在調整維度大小時不會清空數組。
Dim receipe ReDim receipes(0) receipes(0) = "chicken soup" 'Chicken Soup ReDim Preserve receipes(1) receipes(1) = "turkey" 'Turkey ReDim Preserve receipes(2) receipes(2) = "mash potatoes" 'Mash Potatoes ReDim Preserve receipes(3) receipes(3) = "yams" 'Yams ReDim Preserve receipes(4) receipes(4) = "stuffing" 'Stuffing For Each receipe In receipes WScript.Echo receipe Next
輸出:
chicken soup turkey mash potatoes yams stuffing
只需在每行末尾添加下划線,如下所示:
recipes = Array("chicken soup",_
"turkey",_
"mash potatoes",_
"yams",_
"stuffing")
注意:但即使在這種情況下, 您也無法為每一行添加評論。
這是我最終使用的解決方案,感謝Lankymart建議ReDim,它完全符合我的要求。 我可以有一個添加到數組中的項目列表,可以完全注釋掉或重新排列。 為了我的目的,代碼用在一個小實用程序中,速度絕對沒有問題。
Dim recipe, recipes
ReDim recipes(0)
Function AddRecipe(v)
If recipes(0) = "" Then
recipes(UBound(recipes)) = v
Else
ReDim Preserve recipes(UBound(recipes)+1)
recipes(UBound(recipes)) = v
End If
End Function
AddRecipe("Ham") 'Honey Glazed
AddRecipe("turkey") 'YUMMY i love turkey
AddRecipe("mash potatoes") 'butter, sour cream, cook 20mins
AddRecipe("yams") 'dont forget the marshmallows
AddRecipe("stuffing") 'celery, jiffy cornbread, broth
For Each recipe In recipes
WScript.Echo "value:" & recipe
Next
因為這:
>> Sub Add2Array(a, v)
>> ReDim Preserve a(UBound(a) + 1)
>> a(UBound(a)) = v
>> End Sub
>> aa = Array()
>> WScript.Echo 0, TypeName(aa), UBound(aa)
>> Add2Array aa, "look, ma - one elm"
>> WScript.Echo 1, TypeName(aa), UBound(aa), aa(0)
>>
0 Variant() -1
1 Variant() 0 look, ma - one elm
這將是一個糟糕的評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.