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

问题描述 投票:0回答:1

我有一个问题是从一个前缀列表中为变量赋值。我要更好地解释一下。在“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”。我猜是因为代码读取了工作表中的字符串,但是它无法将字符串与“Module8”中公共常量中存在的值相关联。您能否建议我如何处理以将公开列表中的值与表单中的字符串相关联?

先感谢您!

string vba excel-vba public type-mismatch
1个回答
2
投票

你可以宁可使用一个集合。

在Module8中:

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

在Workbook中打开方法(为了从程序开始以来初始化常量):

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的字符串,你想要的回报相关值0.12

© www.soinside.com 2019 - 2024. All rights reserved.