VBA -从不同的字符串创建动态变量



我是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&;。知道我怎么得到这个吗?会很有帮助的)。

非常感谢,如果您有任何问题,请不要犹豫。

您不能从片段创建字符串,然后期望运行时使用它作为变量名。
如果您有一个名称和关联值的列表,您可以使用Collection(或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

通过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自动增加开始元素(如果没有显式分配)。

下面的示例代码

  • 分配单个数组(从& Name&quot开始有点棘手)数组的字符串值,例如"EUR")到buy()作为容器数组和
  • 最终对所有枚举货币执行Match
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的索引),如果根本没有找到,则返回一个错误;通过IsNumeric检查no的结果允许只得到有效的结果。

结果在VB编辑器的直接窗口中显示,例如:

EUR           index 5       Found 5 in EUR_BUY
GBP           index 3       Found 5 in GBP_BUY

最新更新