我有一个有趣的问题,即根据数组中的另一个变量引用另一个变量。
以下是我的代码:
昏暗的公司,价格,sdev,平均值,随机
Dim companies
companies = Array("mm", "tgt", "boog")
mm_price = 0
mm_mean = 0
mm_sdev = 0
tgt_price = 0
tgt_mean = 0
tgt_sdev = 0
boog_price = 0
boog_mean = 0
boog_sdev = 0
For i = 1 To 3
company = companies(i)
mean = company & "_mean"
sdev = company & "_sdev"
Next i
现在,当我尝试定义" mean"和" sdev"变量,因为他们不会使用" 0"值,但改为给它字符串名称" mm_mean"等mm_mean = 0,因此,当i = 1时,我想要均值= 0.清除?
谢谢,让我知道。这是一个相当奇怪的问题,代码是从许多不同的函数中删除的,所以如果为什么我没有意义,我很抱歉。我试图让它变得尽可能简单,这样就不会让回答者感到困惑。
答案 0 :(得分:6)
这是一个很好的例子,应该使用自定义数据结构(也称为“记录类型”,“结构”)来将相关数据组合在一起。在VBA中,语法为Type
:
Type Company
Name As String
Price As Currency
Mean As Double
SDev As Double
End Type
Public Sub CalculateCompanyInfo()
Dim companies(3) As Company
companies(0).Name = "mm"
companies(0).Price = 123
companies(1).Name = "tgt"
companies(1).Price = 456
companies(2).Name = "boog"
companies(2).Price = 789
For i As Integer = 0 to UBound(companies)
companies(i).Mean = ...
companies(i).SDev = ...
Next i
End Sub
其中...
表示您需要进行的任何自定义计算才能获得该值。