gpt4 book ai didi

vba - 具有结构的 VBA 中的 IIF

转载 作者:行者123 更新时间:2023-12-04 13:30:29 25 4
gpt4 key购买 nike

我有一个 With 语句来访问我为某些代码开发的结构。该结构(我工作的地方)有男性和女性两个分支,我将一个整数传递给子例程以指定性别。

大致上我有

Type MyDetails
green As Integer
black As Integer
yellow As Integer
blue As Integer
End Type

Type Genders
Males As MyDetails
Females As MyDetails
End Type

Type GlobalData
RegionName As String
Ages(0..100) As Genders
End Type

Public Dim PopData As GlobalData

然后在我的子程序中有

With PopData.Ages(Cur_Age)
If Cur_Sex = 0 Then
... Do the stuff for males
Else
... Do the exact same stuff but for females
End If
End With

所以我的问题是,我是否可以通过将 IIF 语句放入 WITH block 中来摆脱内部 IF 语句......或类似的东西。这主要是一个学术问题,因为代码工作正常......但最好不要复制我的所有代码,只是将所有 .Males. 更改为 的简单区别。女性。在 If Cur_Sex = 0 Then block 的每个部分内。

提前致谢。希望这是有道理的。

我正在添加有问题的实际代码,希望能让它更清楚......

Cur_Eth 是 Current Ethnicity 的缩写DistInfo 是人口种族分布的缩写Cur_Eth_Total 是一个 Double,它是 .D + .M + .I + .N 的总和(对于男性或女性,取决于我何时调用例程)。

With PopData(Cur_CSD).DistInfo
Cur_Rand = Rnd
Cur_Eth = -1
If Cur_Sex = 0 Then
Cur_Eth_Total = .Males.D + .Males.M + .Males.I + .Males.N
Select Case Cur_Rand
Case Is < CDbl(.Males.D) / Cur_Eth_Total
Cur_Eth = 0
Case Is < CDbl(.Males.D + .Males.M) / Cur_Eth_Total
Cur_Eth = 1
Case Is < CDbl(.Males.D + .Males.M + .Males.I) / Cur_Eth_Total
Cur_Eth = 2
Case Else
Cur_Eth = 3
End Select
Else
Cur_Eth_Total = .Females.D + .Females.M + .Females.I + .Females.N
Select Case Cur_Rand
Case Is < CDbl(.Females.D) / Cur_Eth_Total
Cur_Eth = 0
Case Is < CDbl(.Females.D + .Females.M) / Cur_Eth_Total
Cur_Eth = 1
Case Is < CDbl(.Females.D + .Females.M + .Females.I) / Cur_Eth_Total
Cur_Eth = 2
Case Else
Cur_Eth = 3
End Select
End If
End With

最佳答案

IIf 通过它调用方法的效率非常低。只要你在做简单的变量赋值,就没问题,但如果你尝试使用你的测试条件调用函数,你就会遇到麻烦。 IIf 的问题在于,无论条件的 True 或 False 状态如何,它实际上都会评估/执行两个参数。

因此,就代码而言,这可能是分类器,但就执行而言,它的效率非常低。

看例子:

Function test1() As String
MsgBox "Test1 called"
test1 = "test1"
End Function

Function test2() As String
MsgBox "Test2 called"
test2 = "test2"
End Function

Sub Test()

Dim x As String
Dim Y As Long
Dim Z As String

x = 0

Y = IIf(x = 1, 1, 2)
MsgBox Y

'/ Although condition evaluates to false, it will still call test1
'/which is bound to true condition,before calling test2.
Z = IIf(x = 1, test1, test2)
MsgBox Z

End Sub

关于vba - 具有结构的 VBA 中的 IIF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39151915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com