在IF / Else语句中调用Sub(包含Do直到循环)

时间:2019-05-28 22:15:03

标签: vba subroutine

我有一个do until loop,我一直需要在IF/ELSE语句中重复。我想在IF / Else If /中调用sub(包含do until loop)然后用语句代替。请帮助

此代码有效,但我想将每个do until loop压缩成一个sub,可以使用不同的Tfgain值进行调用:

Dim tmin As Double  
Dim hgmin As Double
Dim tf As Double
Dim hmix As Double
Dim hg As Double
Dim i As Double
tmin = -70               'Lowest temperature of fluid on chart (Fahreinhet)
hgmin = 79.66            'Lowest enthalpy(saturated vapor)

tf = InputBox("Enter Lower Temperature [Fahrenheit]")   'Lower temperature of system

i = tmin
hg = hgmin
If tf <= -9 Then
     Do Until i = tf
        hg = hg + 0.15
        i = i + 1
    Loop
ElseIf tf >= -9 And tf <= 60 Then
    Do Until i = -9
        hg = hg + 0.15
        i = i + 1
    Loop
    Do Until i = tf
        hg = hg + 0.125
        i = i + 1
    Loop
End If 
msgbox(hg)
End Sub

下面的代码不起作用,可能是循环卡住,或者给了我hmin而不是hmin + (gain * amount of iterations from tmin to Tf)的值。

Sub main()
    Dim Tf As Double
    Dim i As Double, hg As Double, tmin As Double, hmin As Double

    Tf= InputBox("Enter Lower Temperature Value")
    hmin = 79.66

    hg = hmin
    tmin = -70
    i = tmin

    If Tf <= -9 Then
        Call subby(Tf, 0.15)

    ElseIf Tf >= -9 And Tf <= 60 Then
        Call subby(-9, 0.15)
        Call subby(Tf, 0.125)
    End If
    msgbox(hg)

End Sub

Sub subby(T As Double, gain As Double)
    Dim i As Double, hg As Double, tmin As Double, hmin As Double
    tmin = -70
    hmin = 79.66

    hg = hmin
    i = tmin
    Do Until i = T
        hg = hg + gain
        i = i + 1
    Loop

End Sub

我希望下面的代码尝试该方法在sub main sub语句中调用另一个IF/Else来匹配hg的上述代码值。

1 个答案:

答案 0 :(得分:0)

您尝试移动到子项的问题是您的变量在该子项中不可见。我看到您尝试通过将这些变量声明为locals来“修复”它,但是主要变量没有正确更改吗?

一种解决方法是插入一个模块,然后在其中将变量声明为PUBLIC

Public tmin As Double  
Public hgmin As Double
Public tf As Double
Public hmix As Double
Public hg As Double
Public i As Double

从文档中

  

使用Public语句声明的变量对所有人可用   所有应用程序中所有模块的程序

确保在subby()内部和main()中都消除了重复的变量声明。它们只能在模块中声明。

一种替代方法是将需要访问并更改为方法的所有变量都传递给该方法。您必须决定哪种更容易或更适合您的情况。