我是 VBA 的初學者。我已經關注 SO 多年,但從未真正發布過。我真的很難理解一個概念,并且在別處找不到答案。我想使用一個 for 回圈來回圈這三個陣列,如下所示:
EUR_Buy = (1,2,3,4,5,6)
USD_BUY = (2,4,6,8,10,12)
GBP_BUY = (1,3,5,7,9,11)
curr = (EUR,USD,GBP)
For i = 0 To 2
For j = 0 To 5
If curr(i) & "_BUY" & (j) = 8
MsgBox Yes
End If
Next j
Next i
我唯一得到的是變數的名稱(例如:Eur_Buy(0) 但不是“1”的值。知道如何得到這個值嗎?會很有幫助)。
非常感謝,如果您有任何問題,請不要猶豫。
uj5u.com熱心網友回復:
您不能從片段創建字串,然后期望運行時將其用作變數名。
如果您有名稱和關聯值的串列,則可以使用 a Collection(或 a Dictionary)。
下面的一段代碼讓您了解如何使用它們。
' Create collection and fill it with 3 elements, each holding an array of 6 values
Dim myVars As New Collection
' Elements are added to a collection with add <value>, <key>
myVars.Add Array(1, 2, 3, 4, 5, 6), "EUR_Buy"
myVars.Add Array(2, 4, 6, 8, 10, 12), "USD_BUY"
myVars.Add Array(1, 3, 5, 7, 9, 11), "GBP_BUY"
Dim curr as Variant
Dim j As Long
For Each curr In Array("EUR", "USD", "GBP")
Dim key As String
key = curr & "_BUY"
' You can access an element of a collection with it's key (name) or index.
For j = 0 To 5
If myVars(key)(j) = 5 Then Debug.Print curr, j, "Found 8 in " & key
Next
Next
uj5u.com熱心網友回復:
通過Enum陳述句參考陣列陣列
如果您必須處理更多的貨幣,它可以提高可讀性
- 使用在代碼模塊的頭部定義的列舉并
- 通過主代碼中的這些占位符變數參考陣列陣列(又名鋸齒狀陣列)
- 保存單個貨幣陣列;你可能認為它是一種容器。
Option Explicit ' head of code module
Enum C ' Enum statement allows automatic increments (if no special assignments)
[_Start] = -1
EUR
USD
GBP
LastElement = GBP ' (re-)set to last currency (here GBP), if changed
End Enum
請注意,您可以輕松插入或添加其他貨幣,而無需關心實際數字的進一步代碼,因為會Enum自動增加開始元素(如果未明確分配)。
下面的示例代碼
- 分配單個陣列(從陣列的“名稱”作為字串值開始有點棘手,例如“EUR”)
buy()作為容器陣列和 Match最終對所有列舉貨幣執行 a 。
Sub ExampleCall()
'1) define zero-based buy arrays referenced by Enum values (~> module top)
Dim buy(C.LastElement) ' declare 0-based Array of arrays
buy(C.EUR) = Array("EUR", 1, 2, 3, 4, 5, 6) ' assign the individual arrays
buy(C.USD) = Array("USD", 2, 4, 6, 8, 10, 12)
buy(C.GBP) = Array("GBP", 1, 3, 5, 7, 9, 11)
'2) define a search value
Dim srch As Variant
srch = 5
'3) find value 5
Dim curr As Long
For curr = 0 To C.LastElement
Dim no As Variant
no = Application.Match(srch, buy(curr), 0) ' << Find ordinal element position
If IsNumeric(no) Then ' check for valid findings only
no = no - 1 ' adjust counter as Match returns 1-based numbers
'4) display result of individual sub-array buy(curr)
Debug.Print _
buy(curr)(0), _
"index " & no, _
"Found " & buy(curr)(no) & " in " & buy(curr)(0) & "_BUY"
End If
Next
End Sub
請注意,如果根本沒有發現,則Application.Match始終回傳-1單個陣列中的從1 開始的位置編號(通過減法調整為從 0 開始的索引)或錯誤;檢查no結果IsNumeric允許只獲得有效的發現。
結果在VB編輯器的立即視窗將顯示如下例:
EUR index 5 Found 5 in EUR_BUY
GBP index 3 Found 5 in GBP_BUY
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/339457.html
上一篇:VBA空日期引數
