从带前缀的变量列表中为变量赋值

Assign a value to a variable from a prefixed list of variables

我在为变量分配前缀列表中的值时遇到问题。 我会更好地解释。在 "Module8" 中,我将以下变量设为常量值:

Public Const Europe = 0.12, _
Middle_East= 0.12, _
Africa = 0.185

其他模块也应该可见。在 "Module5" 我有以下几行:

Sub CalcPop()

Sheets("Region").Select

Data = Range("I7:I15").Value
Geo_Region = Data(1, 1)
Population = Data(3, 1)
Extension = Data(4, 1)
S = Data(7, 1)

S = S * (1 - Geo_Region)

现在 "Module5" 中的代码读取名为 "Region" 的 Sheet,其中以字符串形式存在区域(即欧洲、非洲等),因此变量"Geo_Region" 被定义为欧洲、非洲等。 问题是当它出现在 S = S * (1 - Geo_Region) 行时,它给了我 运行-时间错误 '13' "Type Mismatch"。我猜是因为代码读取了 sheet 中的字符串,但无法将字符串与 "Module8" 中的 public 常量中存在的值相关联。 您能否建议我如何继续将 public 列表中的值与 sheet 中的字符串相关联?

提前致谢!

您可以为此使用集合。

在第 8 单元中:

Dim Geo_Region_List As Collection '<-- declaring the variable as global will allow you to access it any time all over your code

在工作簿打开方法中(为了初始化自程序开始以来的常量):

Set Geo_Region_List = New Collection
With Geo_Region_List
    .Add 0.12, "Europe" 
    .Add 0.12, "Middle East"
    .Add 0.185, "Africa"
End With

... 然后,在您的 Module5 中,您访问与键关联的值:

S = S * (1 - Geo_Region_List(Geo_Region))

(我假设 Geo_Region 是一个类似于 Europe 的字符串并且您希望在 return 中关联值 0.12